一道C语言题目(数字模式的识别),高手来找好算法!!!!我的在OJ上提交要超时。
Description 数字的模式是指在一堆给定数字中出现次数最多的数值,如5,5,5,3,3,2,6,4,它的模式就是5。现在你的任务,就是从数字中找到它的模式.
Input 第一行为整数N.从第二行开始为N个整数。对于输入的每个数,有( |input_number| <= 2000000 ).
Output 输出这些数字的模式,如果模式个数不为1,选择它们之中较小的。
Sample Input
10
1 2 3 4 5 6 7 8 9 9
Sample Output
9
超时代码:
#include <stdio.h>
int main()
{
int n,str[2000000];//我是先绛序排列,再找
int i,j,a,g=0,b=0,c;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&str[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(str[j]>str[i])
a=str[j],str[j]=str[i],str[i]=a;
else if(str[i]==str[j])
{
g++;
if(g>=b)
{b=g,c=str[i];}
}
else
g=0;
}
}
printf("%d\n",c);
return 0;
}
求好算法啊!!!~~~
[解决办法]
请问N的大小是多少?程序所要求的时间是多少?没有数据范围,没有时间要求?
[解决办法]
输入值的最大值为2000000,开一个2000000*2的int数组,直接hash然后扫描一遍就可以了。O(n)的算法
[解决办法]
int count = 18; int arr[18] = {10, 5, 5, 1, 1,2,3,4,5,6,7,7,8,100,102,123,10,9}; int exchange = 1; for (int i = 0; i < 17 && exchange; i++) { exchange = 0; for (int j = 0; j< 17-i; j++) { if(arr[j] > arr[j+1]){ exchange = 1; int tmp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = tmp; } } } int descValue = arr[0]; int descCount = 1; int descValueTmp = arr[0]; int descCountTmp = 1; for (int k = 1; k<18; k++) { if(descValueTmp == arr[k]){ descCountTmp ++; } else{ if(descValue == descValueTmp){ descCount = descCountTmp; } else{ if(descCountTmp > descCount){ descValue = descValueTmp; descCount = descCountTmp; } else if(descCountTmp == descCount){ descValue = descValueTmp > descValue ? descValue : descValueTmp; } } descValueTmp = arr[k]; descCountTmp = 1; } } printf("%d", descValue);
[解决办法]