您的位置:首页 > 其它

74. Search a 2D Matrix

2016-04-19 16:29 274 查看
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
.

思路:就是两次二分查找的过程,第一次二分查找确定在哪一行,第二次二分查找确定有没有

代码如下(已通过leetcode)

public class Solution {

public boolean searchMatrix(int[][] matrix, int target) {

int row=findrow(matrix, target, 0, matrix.length-1);

//System.out.println("第"+row+"行");

if(findit(matrix, row, target, 0, matrix[row].length-1)==Integer.MIN_VALUE) return false;

else {

//int position=findit(matrix, row, target, 0, matrix[row].length-1);

//System.out.println("第"+row+"行"+"第"+position+"位");

return true;

}

}

public int findrow(int[][] matrix,int target,int low,int high) {

while(low<=high) {

if(matrix[low][matrix[low].length-1]<target) low++;

else {

return low;

}

}

return low-1;

}

public int findit(int[][] matrix,int row,int target,int low,int high) {

if(low>high) return Integer.MIN_VALUE;

int mid=(low+high)/2;

if(matrix[row][mid]==target) return mid;

else {

if(matrix[row][mid]>target){

high=mid-1;

} else {

low=mid+1;

}

return findit(matrix, row, target, low, high);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: