[CCF] 201612-1 中间数

【思路】先对数组排序,找到中间位置的数,若比其小的数的数量和比其大的数的数量相等,则输出该数,否则输出-1。

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 bool com(int a[],int n,int x)
 6 {
 7     int l = 0,r = 0;
 8     for(int i = 0;i < n/2;i ++)
 9         if(a[i] < x)    l++;
10     for(int i = n-1;i > n/2;i --)
11         if(a[i] > x)    r++;
12     if(l == r)
13         return true;
14     else
15         return false;
16 }
17 int main()
18 {
19     int n;
20     cin>>n;
21     int a[1010];
22     for(int i = 0; i < n; i ++)
23         cin>>a[i];
24     sort(a,a + n);
25     int res = a[n/2];
26     if(com(a,n,res))
27         cout<<res<<endl;
28     else
29         cout<<"-1"<<endl;
30     return 0;
31 }

[CCF] 201612-1 中间数

 

相关文章:

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