Wednesday, February 12, 2014

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. find target row: O(m)
2. binary search that row: O(log n)
3. O(m+log n) time.
Improvement: treat it as an one dimensional array, and then use binary search

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int rowNum = findRow(matrix, target);
        if(rowNum >= matrix.length) return false;
        return binarySearch(matrix[rowNum], target, 0, matrix[0].length-1);
    }
    public Boolean binarySearch(int[] array, int target, int first, int last){
        if(first > last) return false;
        int mid = (first + last) / 2;
        if(array[mid] == target) return true;
        return (binarySearch(array, target, first, mid-1) || binarySearch(array, target, mid+1, last));
    }
    public int findRow(int[][] matrix, int target){
        int row = 0;
        while(!(target>=matrix[row][0] && target<=matrix[row][matrix[0].length-1])){
            row++;
            if(row >= matrix.length) break;
        }
        return row;
    }
}

No comments:

Post a Comment