这是一个典型的计数排序,此处不需要排序,仅仅计数就可以了,该程序有一定难度,尤其是要考虑顺序时,程序提交一次,就通过了,好开心呀! 另外,计数过程的确很精妙,不需要排序,时间复杂度仅为O(n).

#include <iostream>
using namespace std;

int main()
{
	char str[257];
	int times[10];
	int maxTimesNumber, maxTimes;

	while(cin >> str)
	{
		int i;
		memset(times, 0, 10 * sizeof(10));
		for(i = 0; '\0' != str[i]; i++)
		{
			times[str[i] - '0']++;
		}

		maxTimes = 0;
		for(i = 0; '\0' != str[i]; i++)
		{
			if(times[str[i] - '0'] > maxTimes)
			{
				maxTimes = times[str[i] - '0'];
				maxTimesNumber = str[i] - '0';
			}	
		}
		
		/*
		// The following statements fail to consider the order.
			
			for(i = 0; i < 10; i++)
			{
				if(times[i] > maxTimes)
				{
					maxTimes = times[i];
					maxTimesNumber = i;
				}	
			}
		*/

		cout << maxTimesNumber << "," << maxTimes << endl;

	}

	return 0;
}




本文转载:CSDN博客