CCF认证2017121-最小差值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zee_Chao/article/details/87904595

本人初学,水平有限,若有不足,恳请赐教!

可以证明,差值最小的两个数一定是在数轴上距离最近的两个数。因此可以考虑先对输入数据进行排序,然后再求出相邻数据的差值中最小的那个即可。

具体代码如下:

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

using namespace std;

int main()
{
	int n;
	cin >> n;
	vector<int> input(n);
	int ans = INT_MAX;
	for(int i = 0; i < n; i++) cin >> input[i];
	sort(input.begin(), input.end());
	for(int i = 0; i < n - 1; i++)
		ans = min(ans, abs(input[i] - input[i + 1]));
	cout << ans;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Zee_Chao/article/details/87904595