[leetcode]74. Search a 2D Matrix
程序员文章站
2022-07-14 17:57:15
...
Solution 1: binary search
整个二维数组是已经排好序了的。
第一反应是降维,把二维的变成一维数组,然后应用二分搜索法
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0||matrix[0].length==0)return false;
int low=0;
int m=matrix.length;
int n=matrix[0].length;
int hi=m*n-1;
while(low<=hi){
int mid=(low+hi)/2;
int r=mid/n;
int c=mid-r*n;
if(matrix[r][c]==target){
return true;
}
else if(matrix[r][c]>target){
hi=mid-1;
}
else{
low=mid+1;
}
}
return false;
}
}
推荐阅读
-
LeetCode 74. Search a 2D Matrix
-
74. Search a 2D Matrix
-
74. Search a 2D Matrix
-
LeetCode 74. Search a 2D Matrix
-
[leetcode]74. Search a 2D Matrix
-
leetcode -- 74. Search a 2D Matrix
-
LeetCode 74. Search a 2D Matrix
-
[leetcode] 74. Search a 2D Matrix @ python
-
[leetcode]74. Search a 2D Matrix
-
74. Search a 2D Matrix