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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

 

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
 4         // 先根据最后一列二分查找,确定 target 在哪一行。
 5         int n = matrix.size(); //3
 6         int m = matrix[0].size();//4
 7         int low = 0;
 8         int high = n -1 ;
 9         while(low < high) {
10             int mid = low + (high - low) / 2;
11             if (matrix[mid][m-1] < target) {
12                 low = mid + 1;
13             } else if(matrix[mid][m-1] > target) {
14                 high = mid ;
15             } else {
16                 return true;
17             }
18         }
19         // low is the target 行
20         int wanted_row = low;
21         low = 0;
22         high = m - 1 ;
23 
24         while(low < high) {
25             int mid = low + (high - low) /2;
26             if(matrix[wanted_row][mid] < target) {
27                 low = mid + 1;
28             } else if (matrix[wanted_row][mid] > target) {
29                 high = mid ;
30             } else {
31                 return true;
32             }
33         }
34         return matrix[wanted_row][low] == target;
35     }
36 };

 

 




 1 class Solution {
 2     public boolean searchMatrix(int[][] a, int target) {
 3         if (a.length<1)
 4             return false;
 5         int i = 0;
 6         int j = a[0].length-1;
 7         while(i<a.length && j>=0){
 8             if(target==a[i][j])
 9                 return true;
10             else if(target>a[i][j])
11                 i++;
12             else
13                 j--;
14         }
15         return false;
16     }
17 }

 

相关文章:

  • 2021-10-03
  • 2022-12-23
  • 2022-01-26
  • 2021-05-30
  • 2021-09-14
  • 2022-01-26
  • 2021-09-17
猜你喜欢
  • 2022-03-01
  • 2021-08-02
  • 2021-06-24
  • 2021-10-06
相关资源
相似解决方案