Tuesday, March 10, 2015

74. Search a 2D Matrix Leetcode Java

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:
2-D Binary Search
First check which row the target is belong to by binary searching the first column element.
If couldn't find such row, return false.
Then find the target in that row by another binary search. Return false if there is no match for the target.
Time complexity (Olog(Math.max(m,n))
 public boolean searchMatrix(int[][] matrix, int target) {  
     if(matrix==null || matrix.length==0 || matrix[0].length==0) return false;  
     int l=0;  
     int r=matrix.length-1;  
     while(l<=r){  
       int m=(r-l)/2+l;  
       if(matrix[m][0]==target) return true;  
       else if(matrix[m][0]>target) r=m-1;  
       else l=m+1;  
     }  
     if(r<0) return false;  
     int row=r;  
     r=matrix[row].length-1;  
     l=0;  
     while(l<=r){  
       int m=(r-l)/2+l;  
       if(matrix[row][m]==target) return true;  
       else if(matrix[row][m]>target) r=m-1;  
       else l=m+1;  
     }  
     return false;  
   }  

No comments:

Post a Comment