C代码执行速度优化问题

WOLF3057 2009-08-26 04:35:48
问题:
--------------------------------------------------------------------------------
Time Limit:1s Memory limit:64M
--------------------------------------------------------------------------------

An array of length n, with address from 1 to n inclusive, contains entries from the set {1,2,...,n-1} and there's exactly two elements with the same value.Your task is to find out the value.

Input:

Input contains several cases.
Each case includes a number n (1<n<=10^6), which is followed by n integers.
The input is ended up with the end of file.

Output

Your must output the value for each case, one per line.

Sample Input

2
1 1
4
1 2 3 2

Sample Output
1
2


下面是我自己写的一段代码

#include <stdio.h>

int main()
{
int n,*data,p;

while (scanf("%d",&n)!=EOF)
{
data = (int *)malloc(sizeof(int)*n);

while(n--)
{
scanf("%d",&p);
if(*(data+p) == 1)
{
printf("%d\n",p);
break;

}
*(data + p) = 1;
}
free(data);
}
return 0;
}


执行时间总是2s,有哪位dx知道如何优化这段代码的,或者自己写一个高效率的实现代码出来的,
望高手指点啊!!!
...全文
110 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
WOLF3057 2009-08-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 erwin1984 的回复:]
这个用数学方式做就行了,不需要计数。

s1 = sum(1+2...+n) = n*(n+1)/2;
s2 = sum(input); // 所有输入数字的和

而 s1 - s2 == n - res  所以有:
result = n + s2 - s1;
[/Quote]

就是这种方法
whg01 2009-08-26
  • 打赏
  • 举报
回复
文件最好一次读入到内存中,如果不能一次读入,考虑分2、3次。每次读一点是很慢的。然后用位图的方法来判断是否有相等的。
erwin1984 2009-08-26
  • 打赏
  • 举报
回复
这个用数学方式做就行了,不需要计数。

s1 = sum(1+2...+n) = n*(n+1)/2;
s2 = sum(input); // 所有输入数字的和

而 s1 - s2 == n - res 所以有:
result = n + s2 - s1;

70,012

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧