- 程序有所改变。发帖如还有问题请报告
- 【征集】西西河的经济学,及清流措施,需要主动参与者,『稷下学宫』新认证方式,24年网站打算和努力目标
主题:求教大家一个算法问题 -- looklook
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.
- 相关回复 上下关系8
🙂Use Hashset. 1 bigbug 字22 2006-05-05 12:23:29
🙂这是个algorithm问题,不能这样解决 looklook 字343 2006-05-05 12:44:43
🙂bigbug可能写得比较简单吧 1 【子衿】 字226 2006-05-05 13:13:21
🙂Implementation using HashSet.
🙂hash是对的。 但是, 你的contains()如何最快实现呢! 萝卜酒 字0 2006-05-06 01:12:11
🙂There are always two solutions for the classic issue. bigbug 字263 2006-05-07 16:20:38
🙂不是这样解决的 looklook 字132 2006-05-05 13:42:39
🙂先排再找有什么问题吗? 1 孔老大 字224 2006-05-05 16:14:31