Leetcode 74

Question

Solution

因为matrix是排好序的,将其转化为一维列表,然后用二分法查找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
if not matrix[0]:
return False
temp = [elem for row in matrix for elem in row]
first, last = 0, len(temp) - 1
while first <= last:
mid = (first + last) // 2
if temp[mid] == target:
return True
elif temp[mid] < target:
first = mid + 1
else:
last = mid - 1
return False