2017春招笔试编程题-买帽子

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

输入:

首先输入一个正整数N(N<=50),接下来输入N个数表示每顶帽子的价格(价格均为正整数,且小于等于1000);

输出:

如果存在第三便宜的帽子,请输出这个价格是多少?否则输出-1.


输入例子:

10

10 10 10 10 20 20 30 30 40 40 

输出:

30


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

using namespace std;
int main()
{
	int n = 0;
	while (cin >> n)
	{
		vector <int> price(n, 0);//初始化n个0;
		for (int i = 0; i<n; i++)
			cin >> price[i];
		sort(price.begin(), price.end());
		int cnt = 1;
		int ps = 1;
		for (; ps<price.size(); ps++)
		{
			if (price[ps]>price[ps - 1])
				++cnt;
			if (cnt == 3)
				break;
		}
		if (cnt == 3)
			cout << price[ps] << endl;
		else
			cout << "-1" << endl;
	}
	return 0;
}

度度熊回家问题

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

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


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
	int n = 0;
	int result = 0;
	int maxx = 0;
	while (cin >> n)
	{
		vector <int> vec(n, 0);
		for (int i = 0; i<n; i++)
			cin >> vec[i];
		
		for (int i = 0; i<n; i++)
			result += abs(vec[i] - vec[i - 1]);		
		for (int i = 1; i<n - 1; i++)
			maxx = max(maxx, abs(abs(vec[i + 1] - vec[i]) + abs(vec[i] - vec[i - 1]) - abs(vec[i + 1] - vec[i - 1])));
	}
	return (result-maxx);
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值