mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-05 15:12:22 +00:00
添加Go语言题解
This commit is contained in:
@@ -83,3 +83,30 @@ class Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func searchMatrix(matrix [][]int, target int) bool {
|
||||
if len(matrix) == 0 {
|
||||
return false
|
||||
}
|
||||
row, col := len(matrix), len(matrix[0])
|
||||
// 将二维数组拉平为一维。
|
||||
l, r := 0, row * col - 1
|
||||
for l <= r {
|
||||
m := l + (r - l) / 2
|
||||
// 将一维的坐标转换为二维
|
||||
x, y := m / col, m % col
|
||||
if matrix[x][y] == target {
|
||||
return true
|
||||
} else if matrix[x][y] < target {
|
||||
l = m + 1
|
||||
} else if matrix[x][y] > target {
|
||||
// 二分查找时,把所有的情况都要写出来,避免直接else
|
||||
r = m - 1
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user