欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 74 搜索二维矩阵

程序员文章站 2022-05-21 16:13:43
...
// 二分,当成一维数组,下标转换

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

        int l = 0;
        int r = n * m;
        int mid;
        int row;
        int col;
        while(l < r){
            mid = (l + r) / 2;
            row = mid / m;
            col = mid % m;
            if (target < matrix[row][col]) {
                r = mid;
            }else if (target == matrix[row][col]){
                return true;
            }else {
                l = mid + 1;
            }
        }
        return false;
    }
}