Codechef Racing Horses题解

找一个数组中两数之间最小的不同值。

思路:

1 排序

2 后前相减,比較得到最小不同值

三个数甚至很多其它数之间的不同值都是这么求了,时间效率都是O(nlgn) -- 排序使用的时间

原题:

http://www.codechef.com/problems/HORSES

笔者的练习文件非常大,所以还是使用类好,能够降低变量名和函数名的冲突。

namespace有时候也不好用。

#include <cstdio>
#include <algorithm>
#include <assert.h>
using std::qsort;

class RacingHouse
{
	const static int MAX_INT = -((1<<31)+1);
public:
	int scanInt()
	{
		char c = getchar();
		while (c < '0' || '9' < c)
		{
			c = getchar();
		}
		int num = 0;
		while ('0' <= c && c <= '9')
		{
			num = (num<<3) + (num<<1) + c - '0';
			c = getc(stdin);
		}
		return num;
	}
	void run()
	{
		auto cmp = [](const void *a, const void *b)
		{
			return *(int *)a - *(int *)b;
		};

		int T = scanInt();
		while (T--)
		{
			int n = scanInt();
			assert(1 < n);
			int *A = new int[n];
			for (int i = 0; i < n; i++)
			{
				A[i] = scanInt();
			}
			qsort(A, n, sizeof(int), cmp);
			int minDiff = MAX_INT;
			for (int i = 1; i < n; i++)
			{
				if (A[i] - A[i-1] < minDiff)
				{
					minDiff = A[i] - A[i-1];
				}
			}
			printf("%d\n", minDiff);
		}
	}
};

int racingHouseRun()
{
	RacingHouse rh;
	rh.run();
	return 0;
}



posted @ 2018-03-03 19:46  llguanli  阅读(117)  评论(0编辑  收藏  举报