CCF 201612-1 中间数【使用vector容器排序】

一、题目

在这里插入图片描述

二、解析

由题可知,若中间数存在,则它一定在输入序列的正中间。

使用vector容器保存输入的序列并用sort排序(见博客:CCF 201903-1 小中大【使用vector容器排序】),然后使用两个iterator:front和back,从序列的中间分别向前/向后遍历,根据情况分类讨论。

三、代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int n;
vector<int> v;

struct cmp {
	bool operator() (int d1, int d2)
	{
		return d1 < d2;
	}
};

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++) {
		int num;
		cin >> num;
		v.push_back(num);
	}
	sort(v.begin(), v.end(), cmp());
	/*for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
		cout << *it << " ";
	cout << endl;*/

	vector<int>::iterator front;
	vector<int>::iterator back;

	if (n % 2 == 0) {
		front = v.begin() + n / 2 - 1;
		back = v.begin() + n / 2;
	}
	else {
		front = v.begin() + n / 2;
		back = v.begin() + n / 2;
	}
	//cout<<*front<<" "<<*back<<endl;

	if (*front != *back)
		cout << "-1" << endl;
	else {
		int mid = *front;
		while (front != v.begin() & back != (v.end() - 1) & *front == *back) {
			front -= 1;
			back += 1;
		}
		if (*front != *back) {
			if (*front == mid | *back == mid)
				cout << "-1" << endl;
			else
				cout << mid << endl;
		}
		else
			cout << mid << endl;
	}
	return 0;
}

输入:

6
2 6 5 6 3 5

输出:

5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值