1901. 寻找峰值 II

1901. 寻找峰值 II

解法一: 暴力

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func findPeakGrid(mat [][]int) []int {
m := len(mat)
n := len(mat[0])
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
if (r == 0 || mat[r][c] > mat[r - 1][c]) &&
(r == m - 1 || mat[r][c] > mat[r + 1][c]) &&
(c == 0 || mat[r][c] > mat[r][c - 1]) &&
(c == n - 1 || mat[r][c] > mat[r][c + 1]) {
return []int{r, c}
}
}
}
return []int{}
}

解法二: 二分查找

go
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
func findPeakGrid(mat [][]int) []int {
m := len(mat)
left := 0
right := m - 1
for left < right {
mid := ((right - left) >> 1) + left
i := maxIndex(mat[mid])
if mat[mid][i] < mat[mid + 1][i] {
left = mid + 1
} else {
right = mid
}
}
return []int{left, maxIndex(mat[left])}
}

func maxIndex(nums []int) int {
ans := 0
for i, num := range nums {
if nums[ans] < num {
ans = i
}
}
return ans
}
作者

wuhunyu

发布于

2023-12-19

更新于

2023-12-19

许可协议