求一组数中的第二大数问题:用分治算法实现从一组数据中找出第二大的数,并将结果输出。 c++
时间: 2024-02-17 11:02:29 浏览: 35
好的,下面是用 C++ 实现求一组数中的第二大数的分治算法代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
int findSecondMax(vector<int>& nums, int left, int right) {
if (left >= right) {
return INT_MIN;
}
if (left + 1 == right) {
return nums[left];
}
int mid = left + (right - left) / 2;
int leftMax = findSecondMax(nums, left, mid);
int rightMax = findSecondMax(nums, mid, right);
int maxVal = max(leftMax, rightMax);
int secondMax = INT_MIN;
for (int i = left; i < right; i++) {
if (nums[i] != maxVal && nums[i] > secondMax) {
secondMax = nums[i];
}
}
return secondMax;
}
int main() {
vector<int> nums = {3, 5, 2, 8, 10, 11, 4};
int secondMax = findSecondMax(nums, 0, nums.size());
cout << "Second Max: " << secondMax << endl; // Output: 10
return 0;
}
```
希望能帮到你!
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)