度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少?
输入描述:
首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于1000)
输出描述:
如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1
输入例子:
10 10 10 10 10 20 20 30 30 40 40
输出例子:
30
对于这个题目,用Set容器进行查重排序,相关用法可以看 http://blog.csdn.net/yas12345678/article/details/52601454 这个里面对于set的用法解析的很详细。#include <iostream> #include <set> using namespace std; int main() { int n,a; set<int> cap; //进行查重排序 cin >>n; for (int i = 0;i<n;i++) { cin >>a; cap.insert(a); } set<int>::iterator it;//it为指针 int num = 0; for (it = cap.begin();it != cap.end();it++) //挨个找,第三个输出 { num++; if (num == 3) cout<<*it<<endl; } if (num<3) cout <<"-1"<<endl; }