您的位置:首页 > 其它

LeetCode 74 Search a 2D Matrix

2016-05-25 10:43 423 查看
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
.

思路:矩阵的每一行的最小数据也大于前一行的最大数据,就是任何数据都大于前一行的所有数据。因此可以把矩阵按行顺序展开,数据递增排序,二分查找即可。展开后,第k个位置的数据,在矩阵中的位置为:matrix[k/ n][k % n],n代表矩阵的总列数。时间复杂度为O( log(m*n) )

public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0) return false;
int m = matrix.length, n = matrix[0].length;
int low = 0, hight = m * n;
while (low < hight) {
int mid = low + (hight - low) / 2;
int vlaue = matrix[mid / n][mid % n];
if (vlaue == target) return true;
else if (vlaue < target) low = mid + 1;
else hight = mid;
}
return false;
}

更简单,更快的做法,参考LeetCode 240的解法,时间复杂度为O(m+n).

public boolean searchMatrix2(int[][] matrix, int target) {
if (matrix.length == 0) return false;
int m = 0, n = matrix[0].length - 1;
while (m < matrix.length && n >= 0) {
int x = matrix[m]
;
if (target == x) return true;
else if (target < x) n--;
else m++;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode wr 查找