leecode 240. 搜索二维矩阵 II

// start our "pointer" in the bottom-left

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        // start our "pointer" in the bottom-left
        int row = matrix.length-1;
        int col = 0;

        while (row >= 0 && col < matrix[0].length) {
            if (matrix[row][col] > target) {
                row--;
            } else if (matrix[row][col] < target) {
                col++;
            } else { // found it
                return true;
            }
        }

        return false;
    }
}

从右上角开始移动

    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length==0)
            return false;
        int i = 0;
        int j = matrix[0].length;
        while( i<matrix.length || j>=0 ){
            if(matrix[i][j]==target)
                return true;
            else if(matrix[i][j]>target)
                j--;
            else
                i++;
        }
        return false;
    }
原文地址:https://www.cnblogs.com/kpwong/p/14657930.html