Post

Search a 2D Matrix

LeetCode https://leetcode.cn/problems/search-a-2d-matrix/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int i = 0;
        int j = row * col -1;
        while (i <= j) {
            int mid = i + (j - i) / 2;
            int r = mid / col;
            int c = mid % col;
            if (matrix[r][c] == target) {
                return true;
            } else if (matrix[r][c] > target) {
                j = mid - 1;
            } else {
                i = mid + 1;
            }
        } // end while
        return false;
    }
}

Complexity

  • Time = O(log(m*n)) (m, n 是行长度列长度)
  • Space = O(1)
This post is licensed under CC BY 4.0 by the author.