74. Search a 2D Matrix

Posted gopanama

tags:

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

用Binary search 先搜索row 再搜索col

 

 

 

 1 //Old
 2 class Solution {
 3     public boolean searchMatrix(int[][] matrix, int target) {
 4         if(matrix == null ) return false;
 5         int row = matrix.length;
 6         if(row == 0) return false;
 7         int col = matrix[0].length;
 8         if(col == 0) return false;
 9         int record = -1;
10         for(int i = 0; i < row; i++) {
11             if(matrix[i][col - 1] >= target ) {
12                 record = i;
13                 break;
14             }
15         }
16         if(record == -1) {
17             return false;
18         }else {
19             for(int i = 0; i < col; i++) {
20                 if(matrix[record][i] == target) {
21                     return true;
22                 }
23             }
24         }
25         return false;
26         
27     }
28 }
29 
30 //New
31 class Solution {
32     public boolean searchMatrix(int[][] matrix, int target) {
33         if(matrix == null ) return false;
34         int row = matrix.length;
35         if(row == 0) return false;
36         int col = matrix[0].length;
37         if(col == 0) return false;
38         int lo = 0, hi = row - 1;
39         while(lo <= hi) {
40             int mid = lo + (hi-lo) / 2;
41         
42             if(matrix[mid][0] == target) {
43                 return true;
44             }else if(matrix[mid][0] < target) {
45                 lo = mid + 1;
46             }else {
47                 hi = mid - 1;
48             }
49         }
50         if(hi < 0) return false;
51         int lo1 = 0, hi1 = col - 1;
52         while(lo1 <= hi1) {
53             int mid = lo1 + (hi1-lo1) / 2;
54             if(matrix[hi][mid] == target) {
55                 return true;
56             }else if(matrix[hi][mid] < target) {
57                 lo1 = mid + 1;
58             }else {
59                 hi1 = mid - 1;
60             }
61         }
62         return false;
63     }
64 }

 

以上是关于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