您的位置:首页 > 其它

[leetcode] Search a 2D matrix

2015-02-07 02:57 260 查看
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
.

思路:很容易发现所有数已经排过序,则可以用二分查找,注意将index转化成二维坐标。

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