74. 搜索二维矩阵

先对行进行二分查找,最后的lowR第一个大于target所在行的行数,因此target所在行应该在lowR-1,如果lowR=0,由于没有-1行,所以不存在target,要返回false

特别注意程序中及时return.

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        // boolean ans = false;
        int lowR = 0, highR = matrix.length, lowC = 0, highC = matrix[0].length;
        while (lowR < highR) {
            int midR = (lowR + highR) / 2;
            if (target == matrix[midR][0]) {
                // ans = true;
                return true;
            } else if (target > matrix[midR][0]) {
                lowR = midR + 1;
            } else {
                highR = midR;
            }
        }
        if (lowR == 0) return false;
        while (lowC < highC) {
            int midC = (lowC + highC) / 2;
            if (target == matrix[lowR - 1][midC]) {
                // ans = true;
                return true;
            } else if (target > matrix[lowR - 1][midC]) {
                lowC = midC + 1;
            } else {
                highC = midC;
            }
        }
        return false;
    }
}

你可能感兴趣的:(LeetCode,矩阵,算法,数据结构)