Search a 2D Matrix, Leetcode 解题笔记

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.

特点太明显了,看完题应该瞬间反应到二分法,先沿着行找一次,再沿着列找一次。

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length;  
        if(row ==0) return false;  
        int col = matrix[0].length;  
        if(col ==0) return false;
        if(target< matrix[0][0]) return false; 
        int start = 0;
        int end = matrix.length-1;
        int rownum = 0;
        int mid = -1; 
        while(start <= end){
            mid = (start + end)/2;
            if(matrix[mid][0] == target){
                return true;
            }
            else if(matrix[mid][0] > target){
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }
        rownum = end;
        start = 0;
        end = matrix[0].length -1 ;
        while(start <= end){
            mid = (start + end)/2;
            if(matrix[rownum][mid] == target){
                return true;
            }
            else if(matrix[rownum][mid] > target){
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }
      
        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