Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Check if matrix of integers contains a number
- * @param mat - a two-dimentional array to seach in
- * @param num - the number to seach for
- * @return true if the number is found, false otherwise
- *
- * Time Compelxity - O(logn)
- * Space Complexity - O(1)
- */
- public static boolean search(int[][] mat, int num)
- {
- // low and high values to track searching bounds
- int rL = 0, rH = mat.length;
- int cL = 0, cH = mat.length;
- // center pivot
- int pR = rL + (rH - rL)/2;
- int pC = cL + (cH - cL) / 2;
- while(mat[pR][pC] != num)
- {
- // if the lower and upper bounds are equals we are done scanning
- if(rH == rL || cH == cL)
- return false;
- // setting pivots to matrix center value
- pR = rL + (rH - rL)/2;
- pC = cL + (cH - cL) / 2;
- // checking lower left quadrant
- if(num >= mat[pR][cL])
- {
- rL = pR;
- cH = pC;
- }
- // checking lower right quadrant
- else if(num >= mat[pR][pC])
- {
- rL = pR;
- cL = pC;
- }
- // checking upper right quadrant
- else if(num >= mat[rL][pC])
- {
- rH = pR;
- cL = pC;
- }
- // checking upper left quadrant
- else
- {
- rH = pR;
- cH = pC;
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement