Java for LeetCode 074 Search a 2D Matrix

时间:2022-02-17 09:13:10

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target = 3, return true.

解题思路:

二分查找即可,JAVA实现如下:

    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+down)/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];
}

当然,也可以只用两个指针表示,JAVA实现如下:

	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;
}