240. Search a 2D Matrix II

matrix = [
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
target = 6

以第一行最右边元素(刚好是第一行和最后一列的中间值)作为开始点,小于它减去col,大于加上row,新的点成为新的基准点,再向下或者向左走。注意边界!!!!

public boolean searchMatrix(int[][] matrix, int target) {
    if (matrix.length == 0 || matrix[0].length == 0) return false;

    int row = 0, col = matrix[0].length - 1;

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

results matching ""

    No results matching ""