Thursday, May 22, 2014

Leetcode: 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

Using two binary searches: one to find the row to look into and then one internal to the row.

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        //Find the row 
        int start = 0;
        int end = matrix.length-1;
        if(matrix.length==0 || matrix[0].length == 0 || matrix[0][0]>target)
            return false;
        while(start < end)
        {
            int midpoint = (start+end+1)/2;
            if (matrix[midpoint][0]==target)
                return true;
            if (matrix[midpoint][0]>target)
                end = midpoint-1;
            else
                start = midpoint;
        }
        int row = start;

        //Binary search internal to the row
        start = 0;
        end =  matrix[row].length-1;
        
        while(start <= end)
        {
            int midpoint = (start+end)/2;
            if (matrix[row][midpoint]==target)
                return true;
            if (matrix[row][midpoint]<target)
                start = midpoint+1;
            else
                end = midpoint-1;
                
        }
        return false;
    }
}

No comments :

Post a Comment