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

Commit f32663a

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

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,45 @@ class Solution:
289289
return False
290290
```
291291

292+
### 解法二
293+
294+
将矩阵拉成直线后进行二分查找。
295+
296+
```go
297+
func searchMatrix(matrix [][]int, target int) bool {
298+
m := len(matrix)
299+
if m == 0 {
300+
return false
301+
}
302+
n := len(matrix[0])
303+
if n == 0 {
304+
return false
305+
}
306+
307+
length := m * n
308+
left := 0
309+
right := length - 1
310+
311+
for left <= right {
312+
middle := left + (right - left) / 2
313+
// fmt.Printf("%d", middle)
314+
row := middle / n
315+
column := middle % n
316+
num := matrix[row][column]
317+
318+
if num > target {
319+
right = middle - 1
320+
} else if num < target {
321+
left = middle + 1
322+
} else {
323+
return true
324+
}
325+
}
326+
327+
return false
328+
}
329+
```
330+
292331
## 162. 寻找峰值
293332

294333
[原题链接](https://leetcode-cn.com/problems/find-peak-element/)

0 commit comments

Comments
 (0)