西西河

主题:求教大家一个算法问题 -- looklook

共:💬24 🌺10 新:
全看分页树展 · 主题 跟帖
家园 Implementation using HashSet.

Yes, I put it too simply.

Here is how you can do it:

boolean hasDuplicate(int[] a) {

HashSet hs = new HashSet();

for (int i = 0; i < a.length; ++i) {

if (hs.contains(a[i]) {

return true;

}

else {

hs.add(a[i]);

}

}

return false;

}

Here is some Javadoc for HashSet class:

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.

So, as you can see, the algorithm takes O(n) time. There is no need for sorting according to the problem requirement.

Of course, you can also define the method to return the actual duplicate number if you want.

全看分页树展 · 主题 跟帖


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河