Thursday, November 19, 2015

[leetcode]Search a 2D matrix

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int place = binarySearchColumn(matrix, target);
        if (place != matrix.length && matrix[place][0] == target) return true;
        if (place == 0) return false;
        int location = binarySearchRow(matrix[place-1], target);
        return location != matrix[place-1].length && matrix[place-1][location] == target;
    }
    private int binarySearchRow(int row[], int target){
        int left = 0;
        int right = row.length-1;
        while (left <= right){
            int mid = (left+right)/2;
            if (row[mid] > target){
                right = mid-1;
            }else if (row[mid] < target){
                left = mid+1;
            }else{
                return mid;
            }
        }
        return left; 
    }
    
    private int binarySearchColumn(int matrix[][], int target){
        int left = 0;
        int right = matrix.length-1;
        while (left <= right){
            int mid = (left+right)/2;
            if (matrix[mid][0] > target){
                right = mid-1;
            }else if (matrix[mid][0] < target){
                left = mid+1;
            }else{
                return mid;
            }
        }
        return left;
    }
}

No comments:

Post a Comment