Tuesday, December 22, 2015

[leetcode]Search a 2D Matrix II

不知是否最优 。。。 从右上角开始搜 大于 向右走 小于向下走
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }
        int row = 0;
        int col = matrix[0].length-1;
        while (row >= 0 && row < matrix.length 
              && col >= 0 && col < matrix[0].length){
            if (matrix[row][col] == target) return true;
            if (matrix[row][col] > target) col--;
            else row++;
        }
        return false;
    }
}

No comments:

Post a Comment