074._search_a_2d_matrix.md 2.0 KB
Newer Older
K
KEQI HUANG 已提交
1
### 74. Search a 2D Matrix
K
KEQI HUANG 已提交
2 3 4 5 6 7

题目:
<https://leetcode.com/problems/search-a-2d-matrix/>


难度:
K
KEQI HUANG 已提交
8
Medium
K
KEQI HUANG 已提交
9 10


K
KEQI HUANG 已提交
11
思路:
K
KEQI HUANG 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
想过将```2D matrix```看成一个大```sorted list```,代码如下:
```python
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        row = len(matrix)
        col = len(matrix[0]) if row else 0
        l, r = 0, row * col - 1
        while l <= r:
            mid = l + ((r - l) >> 2)
            if target > matrix[mid/col][mid%col]:
                l = mid + 1
            elif target < matrix[mid/col][mid%col]:
                r = mid - 1
            else:
                return True
        return False
```

K
KEQI HUANG 已提交
35

K
KEQI HUANG 已提交
36
但是后面觉得不行,
K
KEQI HUANG 已提交
37 38
原因如下:
1. m * n may overflow for large m and n; 
K
KEQI HUANG 已提交
39
2. it will use multiple expensive operations such as / and %
K
KEQI HUANG 已提交
40

K
KEQI HUANG 已提交
41 42 43 44 45





K
KEQI HUANG 已提交
46
因此二分Search,``` binary search by row first, then binary search by column.```
K
KEQI HUANG 已提交
47 48


K
KEQI HUANG 已提交
49
```python
K
KEQI HUANG 已提交
50 51 52 53 54 55 56
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
K
KEQI HUANG 已提交
57
        if not matrix or not matrix[0]:
K
KEQI HUANG 已提交
58
            return False
K
KEQI HUANG 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        row = len(matrix)
        col = len(matrix[0]) if row else 0
        l, r = 0, row - 1
        while l <= r:
            mid_row = l + ((r - l) >> 2)
            if matrix[mid_row][0] <= target <= matrix[mid_row][-1]:
                m, n = 0, col - 1
                while m <= n:
                    mid_col = m + ((n - m) >> 2)
                    if matrix[mid_row][mid_col] > target:
                        n = mid_col - 1
                    elif matrix[mid_row][mid_col] < target:
                        m = mid_col + 1
                    else:
                        return True
                return False
            elif target < matrix[mid_row][0]:
                r = mid_row - 1
K
KEQI HUANG 已提交
77
            else:
K
KEQI HUANG 已提交
78 79
                l = mid_row + 1
        return False
K
KEQI HUANG 已提交
80
            
K
KEQI HUANG 已提交
81
```