74. Search a 2D Matrix

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了74. Search a 2D Matrix相关的知识,希望对你有一定的参考价值。

基本上就是binary search,我掌握的还是不错的

先确定行,后确定列

 1     public boolean searchMatrix(int[][] matrix, int target) {
 2         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
 3             return false;
 4         }
 5         int low = 0;
 6         int high = matrix.length - 1;
 7         while(low <= high) {
 8             int mid = low+(high-low)/2;
 9             if(matrix[mid][0] > target) {
10                 high = mid-1;
11             } else if(matrix[mid][0] < target) {
12                 low = mid+1;
13             } else {
14                 return true;
15             }
16         }
17         if(high < 0) {
18             return false;
19         }
20         int l = 0;
21         int r = matrix[0].length-1;
22         while(l <= r) {
23             int mid = l+(r-l)/2;
24             if(matrix[high][mid] < target) {
25                 l = mid+1;
26             } else if(matrix[high][mid] > target) {
27                 r = mid-1;
28             } else {
29                 return true;
30             }
31         }
32         return false;
33     }

bug记录:

1.high = length - 1.千万不要忘了减一,我上下两次都忘了

2.当比matrix最小里面还小的时候,注意判断,即17-19行

以上是关于74. Search a 2D Matrix的主要内容,如果未能解决你的问题,请参考以下文章

74. Search a 2D Matrix

74. Search a 2D Matrix

74. Search a 2D Matrix

74. Search a 2D Matrix

74. Search a 2D Matrix

74. Search a 2D Matrix