求n个整数中倒数第二小的数。 每一个整数都独立看成一个数,比如,有三个数分别是1,1,3,那么,第二小的数就是1。c++
时间: 2024-02-25 21:53:52 浏览: 17
下面是一种常规做法的C++代码实现:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
sort(nums.begin(), nums.end());
int cnt = 1, idx = 0;
while (cnt <= 2 && idx < n) {
if (nums[idx] != nums[idx - 1] || idx == 0) {
cnt++;
}
idx++;
}
if (cnt == 3) {
cout << nums[idx - 1] << endl;
} else {
cout << "不存在倒数第二小的数" << endl;
}
return 0;
}
```
首先读入n个整数并存储到一个vector中,然后对这些数进行排序。
接着,遍历排序后的数组,用cnt记录当前数不同的个数,idx记录当前遍历到的位置。如果cnt等于3,那么当前数就是倒数第二小的数,输出并结束程序;否则,继续遍历数组。
需要注意的是,当数组中有重复的数时,需要特殊处理,避免重复计数。
这个算法的时间复杂度为O(n log n),因为需要进行一次排序。