public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
if (matrix == null) return false;
int row = matrix.length;
if (row == 0) return false;
int column = matrix[0].length;
int start = 0;
int end = row - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (matrix[mid][0] == target) start = mid;
else if (matrix[mid][0] > target) end = mid;
else start = mid;
}
int numLine = 0;
int low = 0;
int high = column - 1;
if (matrix[end][0] <= target) numLine = end;
else if (matrix[start][0] <= target) numLine = start;
else return false;
while (low + 1 < high) {
int mid = low + (high - low) / 2;
if (matrix[numLine][mid] == target) return true;
else if (matrix[numLine][mid] > target) high = mid;
else low = mid;
}
if (matrix[numLine][low] == target || matrix[numLine][high] == target)
return true;
else return false;
}
}
public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
if (matrix == null) return false;
int row = matrix.length;
if (row == 0) return false;
int column = matrix[0].length;
int start = 0;
int end = row * column - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
int m = mid / column;
int n = mid % column;
if (matrix[m][n] == target) return true;
else if (matrix[m][n] > target) end = mid;
else start = mid;
}
if (matrix[start / column][start % column] == target ||
matrix[end / column][end % column] == target ) return true;
return false;
}
}
28. Search a 2D Matrix
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 典型老题,从右上角开始搜索,往下是增往左是减。比如.[[1 4],[2 5]]右上角元素即4 ir是行标,ic是列...
- Search a 2D Matrix II这个solution复杂度为O(row + column)主要思想是从右...
- 题目链接 Search a 2D Matrix Write an efficient algorithm that...
- Write an efficient algorithm that searches for a value in...