美文网首页LeetCode
[leetcode] 74. 搜索二维矩阵

[leetcode] 74. 搜索二维矩阵

作者: cptn3m0 | 来源:发表于2019-04-01 23:26 被阅读1次

link

http://www.cnblogs.com/acbingo/p/9374587.html

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        if (m == 0) {
            return false;
        }
        int n = matrix[0].length;
        if (n==0){
            return false;
        }
        int cnt = m * n;
        if (target > matrix[m - 1][n - 1]) {
            return false;
        }
        if (target < matrix[0][0]) {
            return false;
        }


        int l = 0;
        int r = cnt - 1;
        int mid = (l + r) / 2;
        while (l <= r) {
            if (get(matrix, mid, m, n) == target) {
                return true;
            }
            if (get(matrix, mid, m, n) > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
            mid = (l + r) / 2;
        }
        return false;

    }

    // 返回矩阵中的第i个数
    int get(int[][] matrix, int i, int m, int n) {
        int p = i / n;
        int q = i % n;
        return matrix[p][q];

    }
}

相关文章

网友评论

    本文标题:[leetcode] 74. 搜索二维矩阵

    本文链接:https://www.haomeiwen.com/subject/uqeibqtx.html