2015年9月27日星期日

Leetcode 74 Search a 2D Matrix

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.
Solution 1: use binary search column 0 to find the row, then binary search the row to find the target. Time complexity is log(m)+log(n).
 public class Solution {  
   public boolean searchMatrix(int[][] matrix, int target) {  
     int m=matrix.length;  
     if (m==0) return false;  
     int n=matrix[0].length;  
     int lo=0, hi=m-1;  
     while (lo<=hi) {  
       int mid=lo+(hi-lo)/2;  
       if (target==matrix[mid][0]) return true;  
       else if (target<matrix[mid][0]) hi=mid-1;  
       else lo=mid+1;  
     }  
     if (hi<0) return false; //last postion is [hi,lo]=[-1,0]  
     int r=hi;  
     lo=0; hi=n-1;  
     while (lo<=hi) {  
       int mid=lo+(hi-lo)/2;  
       if (target==matrix[r][mid]) return true;  
       else if (target<matrix[r][mid]) hi=mid-1;  
       else lo=mid+1;  
     }  
     return false;  
   }  
 }  

没有评论:

发表评论