天天看點

CCF考試——201612-1中間數

概要

問題描述

  在一個整數序列a1, a2, …, an中,如果存在某個數,大于它的整數數量等于小于它的整數數量,則稱其為中間數。在一個序列中,可能存在多個下标不相同的中間數,這些中間數的值是相同的。

  給定一個整數序列,請找出這個整數序列的中間數的值。

輸入格式

  輸入的第一行包含了一個整數n,表示整數序列中數的個數。

  第二行包含n個正整數,依次表示a1, a2, …, an。

輸出格式

  如果約定序列的中間數存在,則輸出中間數的值,否則輸出-1表示不存在中間數。

樣例輸入

6

2 6 5 6 3 5

樣例輸出

5

樣例說明

  比5小的數有2個,比5大的數也有2個。

樣例輸入

4

3 4 6 7

樣例輸出

-1

樣例說明

  在序列中的4個數都不滿足中間數的定義。

樣例輸入

5

3 4 6 6 7

樣例輸出

-1

樣例說明

  在序列中的5個數都不滿足中間數的定義。

評測用例規模與約定

  對于所有評測用例,1 ≤ n ≤ 1000,1 ≤ ai ≤ 1000。

思路

由于樣例中出現了重複的數,為了減少運作時間與重複計算,可以把數加入到set集合中。剩下的就是周遊統計。

AC代碼

#include <iostream>
#include <set>
using namespace std;

int data[1000];
set<int> s;
int N;

int main()
{
    cin>>N;
    for(int i = 0 ; i < N ; i++){
        cin>>data[i];
        s.insert(data[i]);  
    }

    set<int>::iterator it;
    bool flag = false;
    for(it = s.begin() ; it != s.end() ; it++){
        int greater = 0;
        int lower = 0;
        for(int i = 0 ; i < N ; i++){
            if(data[i] < *it){
                lower++;
            }else if(data[i] > *it){
                greater++;
            }
        }
        if(greater == lower){
            cout<<*it;
            flag = true;
            break;
        }
    }
    if(!flag){
        cout<<-1;
    } 

    return 0;
}           

複制