Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted from the left to the right.
- The first integer of each row was greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [Ten, One,], [23, 30, 34, 50]]
Given Target = 3
, return true
.
Problem Solving Ideas:
Two-point lookup, Java implementation is as follows:
public boolean Searchmatrix (int[][] matrix, int target) { if (matrix.length = = 0 | | matrix[0].length = = 0) return False ; int up = 0, down = matrix.length-1, left = 0, right = Matrix[0].length-1;while (up < down) {if (target>matrix[(up+do WN) (/2][0]) {up= (Up+down)/2;if (target>matrix[up][matrix[0].length-1]) Up++;else break;} else if (target<matrix[(Up+down)/2][0]) down= (Up+down)/2-1;else return true; while (left<right) {if (target>matrix[up][(left+right)/2]) left= (left+right)/2+1;else if (Target<matrix[up] [(Left+right)/2]) right= (left+right)/2-1;else return true;} return target==matrix[up][left]; }
Of course, you can also use only two pointers, Java implementation is as follows:
public boolean Searchmatrix (int[][] matrix, int target) {if (Matrix.length = = 0 | | matrix[0].length = = 0) return false;
int L = 0, r = matrix.length * matrix[0].length-1, mid = 0; while (L < R) { mid = L + (r-l)/2; if (Matrix[mid/matrix[0].length][mid%matrix[0].length] < target) L = mid + 1; else if (Matrix[mid/matrix[0].length][mid%matrix[0].length] > target) r = Mid; else return true; } return Matrix[l/matrix[0].length][l%matrix[0].length] = = target; }
Java for Leetcode 074 Search a 2D Matrix