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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
思路:
两次二分搜索,先二分搜索第一列,找出target所在的行,然后二分搜索该行。
1 public class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 int row = matrix.length; 4 if(row == 0) return false; 5 int col = matrix[0].length; 6 if(col == 0) return false; 7 8 if(target < matrix[0][0]) return false; 9 int start = 0, end = row -1; 10 while(start <= end){ 11 int mid = (start + end)/2; 12 if(matrix[mid][0] ==target) 13 return true; 14 else if(matrix[mid][0] < target) 15 start = mid +1; 16 else 17 end = mid-1; 18 } 19 20 int targetRow = end; 21 start = 0; 22 end = col-1; 23 while(start <= end){ 24 int mid = (start + end)/2; 25 if(matrix[targetRow][mid] ==target) 26 return true; 27 else if(matrix[targetRow][mid] < target) 28 start = mid +1; 29 else 30 end = mid-1; 31 } 32 return false; 33 } 34 }