forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_a_2d_matrix.py
More file actions
34 lines (33 loc) · 1.09 KB
/
search_a_2d_matrix.py
File metadata and controls
34 lines (33 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# -*- coding: utf-8 -*-
class Solution:
"""
@param matrix, a list of lists of integers
@param target, an integer
@return a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if (not matrix) or (target < matrix[0][0]) or (target > matrix[-1][-1]):
return False
start, end = 0, len(matrix)
while start < end:
mid = (start + end) / 2
if matrix[mid][0] < target:
start = mid + 1
elif matrix[mid][0] > target:
end = mid # end是开区间,所以不用减1。
else:
break
if matrix[mid][0] > target: # 确保所有A[mid][0]小于等于target
mid -= 1
i = mid
start, end = 0, len(matrix[0])
while start < end:
mid = (start + end) / 2
if matrix[i][mid] < target:
start = mid + 1
elif matrix[i][mid] > target:
end = mid
else:
return True
return False