度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少?

输入描述:
首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于1000)
输出描述:
如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1
输入例子:
10
10 10 10 10 20 20 30 30 40 40
输出例子:
30

 

这道题想用set集合来做,set有自动排序的功能,而且相同的值只能有一个,所以当把所有的价钱放进set集合后,set中的第三个数就是我们要的价格。当然,在此之前我们需要判断一下set.size()是否小于3,如果小于3,则输出-1。

 

#include <iostream>
#include <algorithm>
#include "string.h"
#include "stdio.h"
#include <vector>
#include<utility>
#include "math.h"
#include <set>
using namespace std;

int main() {
    int n;
    set<int> arr;
    cin>>n;
    if(n>50)
        return 0;
    for(int i = 0;i<n;i++)
    {
        int hat;
        cin>>hat;
        if(hat>1000)
            return 0;
        else
            arr.insert(hat);
    }
    if(arr.size()<3)
    {
        cout<<"-1"<<endl;
        return 0;
    }
    set<int>::iterator ite1 = arr.begin();

    //这里是想把指向第一个元素的迭代器++,使它指向set中的第三个元素   
for(int i=0;i<2;i++) { ite1++; } cout<<*ite1<<endl; return 0; }

 

相关文章:

  • 2021-09-13
  • 2022-01-17
  • 2021-11-29
  • 2021-11-10
猜你喜欢
  • 2022-12-23
  • 2022-03-07
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2021-12-23
  • 2021-12-11
相关资源
相似解决方案