Leetcode 搜索二维矩阵 II

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例:

现有矩阵 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

给定 target = 5,返回 true

给定 target = 20,返回 false

思路:先二分target在哪一行,然后在对行进行二分找在哪一列

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

猜你喜欢

转载自www.cnblogs.com/tijie/p/9954841.html