LeetCode 74 搜索二维矩阵

// 二分,当成一维数组,下标转换

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;
    }
}

 

你可能感兴趣的:(LeetCode,数组,二分,Java,LeetCode,74,搜索二维矩阵)