October 06, 2019

74. Search a 2D Matrix

74. Search a 2D Matrix

二分法 Time = O(log(mn))

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int i = 0;
        int j = matrix.length * matrix[0].length - 1;
        while (i <= j) {  // pay attention here
            int mid = i + (j - i) / 2;
            int row = mid / matrix[0].length;
            int col = mid % matrix[0].length;
            if (matrix[row][col] == target) {
                return true;
            } else if (matrix[row][col] < target) {
                i = mid + 1;
            } else {
                j = mid - 1;
            }
        }
        return false;
    }
}
comments powered by Disqus