您的位置:首页 > 编程语言 > Java开发

[Leetcode] Search a 2D Matrix (Java)

2014-01-14 15:24 459 查看
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
.

在矩阵中找元素,矩阵满足条件:

1)每行都是有序的(递增);

2)下一行的首元素的值>上一行尾元素的值。

二分查找

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length<1||matrix[0].length<1)
return false;
int row = matrix.length;
int col = matrix[0].length;
int low = 0;
int high = row*col-1;
while(low<=high){
int mid = low+((high-low)>>1);
int i = mid/col;
int j = mid%col;
if(matrix[i][j]==target)
return true;
if(matrix[i][j]<target)
low=mid+1;
else
high=mid-1;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: