0
点赞
收藏
分享

微信扫一扫

[LeetCode]Search a 2D Matrix


Question
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​​.

本题难度Medium。

【复杂度】
时间 O(log(MN)) 空间 O(1)

【思路】
我们可以把二维数组想象成一个一维数组,第一行尾连着第二行头,第二行尾连着第三行头…同样是有个最小值最大值,二分得到中间值,通过对中间值取模可以得到对应二维数组的下标。这样,该题就转化为了一维有序数组二分搜索的题了。

【注意】
对于二分查找法,都是将范围分为三部分:中间元素,左边,右边。base case都是:

if(start>end)
return false;

是通过中间元素与target比较来返回true。

【代码】

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
//require
int m=matrix.length;
if(m<1)
return false;
int n=matrix[0].length;
//invariant
return helper(0,m*n-1,target,matrix);

}
private boolean helper(int start,int end,int target,int[][] mat){
//base case
if(start>end)
return false;

int mid=(start+end)/2;
int row=mid/mat[0].length,col=mid%mat[0].length;
if(mat[row][col]==target)
return true;
else if(mat[row][col]>target)
return helper(start,mid-1,target,mat);
else
return helper(mid+1,end,target,mat);
}
}


举报

相关推荐

0 条评论