最普通最容易想到的方法是2次循环,代码如下:
public static boolean containsDuplicate(int[] nums) {
for(int n=0;n<nums.length-1;n++){
for(int m=n+1;m<nums.length;m++){
if(nums[n]==nums[m]){
return true;
}
}
}
return false;
}
缺点:过于暴力,执行效率低,如果数组特别庞大,运行时间过长。
在leetcode上看到一个效率很高的方法,用了Hashset,代码如下:
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i : nums)
if(!set.add(i))// if there is same
return true;
return false;
}
关键字:hashset