Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
,
return true
.
1 public class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 int len =matrix.length; 4 if(len<=0) return false; 5 int len2 = matrix[0].length; 6 if(len2==0) return false; 7 if(target<matrix[0][0]) return false;// don‘t forget this!!! 8 int start = 0, end =len-1; 9 while(start<=end){ 10 int mid = (start+end)/2; 11 if(matrix[mid][0]==target) return true; 12 if(matrix[mid][0]>target){ 13 end = mid-1; 14 } 15 else if(matrix[mid][0]<target){ 16 start = mid+1; 17 } 18 } 19 int row = end;// because target should be greater than target row 20 start = 0; 21 end = len2-1; 22 while(start<=end){ 23 int mid = (start+end)/2; 24 if(matrix[row][mid]==target) return true; 25 else if(matrix[row][mid]<target) start = mid+1; 26 else end = mid-1; 27 } 28 return false; 29 } 30 }
原文:http://www.cnblogs.com/krunning/p/3540026.html