答案 0 :(得分:2)
如果数组已排序:
for(int i=0; i<a.length-1; i++)
if(a[i]==a[i+1])
return true;
return false;
如果数组未排序,请使用缓存:
boolean[] cache=new boolean[N];
Arrays.fill(cache,false); //set all values to false
for(int i=0; i<a.length; i++)
if(cache[a[i]])
return true;
else
cache[a[i]]=true; //mark element a[i] as seen
return false;
在上面,N是数组a中出现的最大值。如果N未知或非常大,或者您的数组包含负值,请使用地图而不是数组作为缓存。
两种解决方案都在O(n)时间内运行。第二种解决方案只需要一个外部缓存来记住我们之前看过的元素。
答案 1 :(得分:0)
你能做到:
Loop on I
Loop on j
If value of a[I] = value of a[j]
Break; /*at least one double found*/
没有
错了..忘了它..