2015年7月27日星期一

[LeetCode] Search a 2D Matrix II

Java Code:

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 
            || matrix[0].length == 0) {
            return false;
        }
        
        int i = 0;
        int j = matrix[0].length - 1;
        
        while (i < matrix.length && j >= 0) {
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] < target) {
                i++;
            } else {
                j--;
            }
        }
        
        return false;
    }
}

reference:
https://leetcode.com/discuss/47660/my-java-solution-using-binary-search

没有评论:

发表评论