CCF CSP-201612-1 中间数(C++)

在这里插入图片描述

#include <cstdio>
#include <algorithm>

using namespace std;

int main(){
    
    
	int n;
	scanf("%d", &n);
	
	int arr[n];
	for(int i=0; i<n; i++){
    
    
		scanf("%d", &arr[i]);
	}
	
	sort(arr, arr+n);
	
	int temp, low=0, high=0;
	if(n % 2 == 0){
    
    
		temp = arr[n/2];
		
		for(int i=0; i<n/2; i++){
    
    
			if(arr[i] < temp){
    
    
				low++;
			}
		}
		for(int i=n/2+1; i<n; i++){
    
    
			if(arr[i] > temp){
    
    
				high++;
			}
		}
	}else{
    
    
		temp = arr[n/2];
		
		for(int i=0; i<n/2; i++){
    
    
			if(arr[i] < temp){
    
    
				low++;
			}
		}
		for(int i=n/2+1; i<n; i++){
    
    
			if(arr[i] > temp){
    
    
				high++;
			}
		}
	}
	
	if(high == low){
    
    
		printf("%d", temp);
	}else{
    
    
		printf("-1");
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45964844/article/details/111029472