add code of 二维数组的二分查找 in go

This commit is contained in:
lincongcong 2021-07-22 23:50:46 +08:00
parent e63c35b170
commit 44004ea38f

View File

@ -52,6 +52,8 @@
#### 题目代码
Java Code:
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
@ -84,3 +86,32 @@ class Solution {
}
```
Go Code:
```go
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
// 行数
row := len(matrix)
//列数
col := len(matrix[0])
// 行数 * 列数 - 1 为右指针
left, right := 0, row * col - 1
for (left <= right) {
mid := left + ((right - left) >> 1)
//将一维坐标变为二维坐标
rownum := mid / col
colnum := mid % col
if matrix[rownum][colnum] == target {
return true
} else if matrix[rownum][colnum] > target {
right = mid - 1
} else if matrix[rownum][colnum] < target {
left = mid + 1
}
}
return false
}
```