一个100*100的网格,网格中有随机0-100数字,找出其中的峰值,返回对应网格下标,C++
时间: 2024-03-26 20:40:25 浏览: 69
好的,以下是一个可能的解法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 返回网格中任意一个峰值的下标
pair<int, int> findPeak(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
int left = 0, right = m - 1;
while (left <= right) {
int mid = (left + right) / 2;
int max_row = 0;
for (int i = 0; i < n; i++) {
if (grid[i][mid] > grid[max_row][mid]) {
max_row = i;
}
}
if ((mid == 0 || grid[max_row][mid] >= grid[max_row][mid - 1])
&& (mid == m - 1 || grid[max_row][mid] >= grid[max_row][mid + 1])) {
return make_pair(max_row, mid);
} else if (mid > 0 && grid[max_row][mid - 1] > grid[max_row][mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return make_pair(-1, -1); // 没有峰值
}
int main() {
vector<vector<int>> grid(100, vector<int>(100));
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
grid[i][j] = rand() % 101;
}
}
pair<int, int> peak = findPeak(grid);
if (peak.first == -1) {
cout << "No peak found" << endl;
} else {
cout << "Peak found at (" << peak.first << ", " << peak.second << ")" << endl;
}
return 0;
}
```
这个解法的时间复杂度是 O(m log n),其中 m 是网格的宽度,n 是网格的高度。它的思路是类似于二分查找的,先找到中间列的最大值,然后比较它和相邻列的大小关系,如果它是峰值就返回,否则就进一步缩小范围。
阅读全文