如何找到第二小元素

How to Find Second Smallest Element

本文关键字:元素 何找      更新时间:2023-10-16

例如,如果我输入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;

您总是可以"正确定义您的算法",但上述方法开发和调试代码的速度更快。