Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ad200eb

Browse files
committed
🐱(binary-search): 74. 搜索二维矩阵
1 parent f103ddf commit ad200eb

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

docs/algorithm/research/binary-search/README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,47 @@ class Solution(object):
247247

248248
ps:看评论有很秀的牛顿迭代法,有空研究下。
249249

250+
## 74. 搜索二维矩阵
251+
252+
[原题链接](https://leetcode-cn.com/problems/search-a-2d-matrix/)
253+
254+
### 解法一
255+
256+
逐行进行二分查找。
257+
258+
```python
259+
class Solution:
260+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
261+
m = len(matrix)
262+
if m == 0:
263+
return False
264+
n = len(matrix[0])
265+
if n == 0:
266+
return False
267+
268+
for i in range(m):
269+
left = 0
270+
right = n - 1
271+
272+
if matrix[i][right] < target:
273+
continue
274+
if matrix[i][left] > target:
275+
return False
276+
277+
if matrix[i][right] == target or matrix[i][left] == target:
278+
return True
279+
280+
while left <= right:
281+
middle = left + (right - left) // 2
282+
if matrix[i][middle] > target:
283+
right -= 1
284+
elif matrix[i][middle] < target:
285+
left += 1
286+
else:
287+
return True
288+
289+
return False
290+
```
250291

251292
## 162. 寻找峰值
252293

0 commit comments

Comments
 (0)