Leetcode–Search a 2D Matrix

The Problem:

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.

Notes:

  1. First find the candidate row, then do binary search

Java Solution

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        for(int i = 0; i < m; i++){
            if(target < matrix[i][0])
                return false;
            else if(target > matrix[i][n-1])
                continue;
            else{
                // in this row
                int low = 0;
                int high = n-1;
                while(low <= high){
                    int mid = (high + low)/2;
                    if(matrix[i][mid] == target)
                        return true;
                    else if (matrix[i][mid] > target)
                        high= mid-1;
                    else 
                        low = mid+1;
                }
                return false;
            }
        }
        return false;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s