如何找到第二小元素
How to Find Second Smallest Element
例如,如果我输入5 4 3 2 1,它会给出1和2,这是正确的,但如果我输入1 2 3 4 5,它会得到1和5,这是错误的。。。。如何解决这个问题?
这个程序通过输入找到最小和第二小的元素。
#include<iostream>
/*This program finds the smallest and second smallest elements through input*/
using namespace std;
/*This program finds the smallest and second smallest elements through input*/
int main(){
float input_from_user=0.0, largest=0.0, smallest_num=0.0, runners_up=0.0;
int count, i;
cout<<"how many swimming records?"<<endl;
cin>>count;
cout<<"enter time: ";
cin>>input_from_user;
smallest_num=input_from_user;
largest=input_from_user;
for (i=1;i<=count;i++){
cout<<"enter time: "<<endl;
cin>>input_from_user;
/*Compare smallest number with latest input*/
if (smallest_num>input_from_user){
runners_up=smallest_num;
smallest_num=input_from_user;
}
}
cout<<"First:"<<smallest_num<<endl;
cout<<"Runners up: "<<runners_up<<endl;
return 0;
}
/*Compare smallest number with latest input*/
if (smallest_num>input_from_user){
runners_up=smallest_num;
smallest_num=input_from_user;
}
上面的代码看起来就是问题所在。
如果input_from_user大于最小num但小于runner_up,则应该更新runner_ump。
/*Compare smallest number with latest input*/
if (runner_up > input_from_user){
if(smallest_num > input_from_user) {
runners_up=smallest_num;
smallest_num=input_from_user;
} else runners_up=input_from_user;
}
最简单的方法是执行以下操作:
vector<float> tms;
for (i=1;i<=count;i++){
cout<<"enter time: "<<endl;
cin>>input_from_user;
tms.push_back(input_from_user);
}
sort(tms.begin(), tms.end());
cout<<"First:"<< tms[0] <<endl;
cout<<"Runners up: "<< tms[1] <<endl;
在访问元素之前,此代码只缺少一些长度检查。
这不是最优的,因为它对所有元素都进行排序,所以还有另一种方法来代替排序——使用额外的"集"只对那些最坏情况下可能是第二小的元素进行排序。在最好的情况下,它只处理前两个元素,不做任何其他事情,在最坏的情况下它只像以前一样对所有元素进行排序。
set<float> out;
out.insert(v[0]);
out.insert(v[1]);
for (auto x = v.begin() + 2; x != v.end(); ++x)
{
auto second = ++out.begin();
if ( *x < *second )
out.insert(*x);
}
auto p = out.begin();
cout << "Smallest: " << *p;
++p;
cout << " Second: " << *p << endl;
您总是可以"正确定义您的算法",但上述方法开发和调试代码的速度更快。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- c++找不到具有相同哈希的无序集合元素
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 扫描阵列特定次数,然后找出元素
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 我如何找出3D容器的元素是什么类型
- 设置要与无序集合一起使用的自定义类 - 在集合中找不到元素
- 找出父型向量元素的子类型
- 如何修改 Kadane 算法以找出贡献最大总和的子数组元素?
- 我如何找出数组中的哪个元素具有最高值
- 找出所有给定数组中公共元素的最佳算法
- 找出flann矩阵类型中最频繁的元素
- C++ for_each循环找不到指向映射元素
- 找出向量中的所有元素是假还是真 c++ 的最快方法
- 找出两个异或最大的元素
- 在c++中,我们如何找出地址和值来自数组中的哪个元素
- 找出两个范围(其中一个已排序)是否有一个公共元素