Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
其实这个题我以前做过类似的,基于HashSet可以很方便的求解;
代码如下:
public static boolean containsDuplicate(int[] nums){
if (nums.length==0||nums.length==1) {
return false;
}
HashSet<Integer> hashSet = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if(hashSet.add(nums[i])==false)
return true;
}
return false;
}

本文介绍了一种使用HashSet来检查整数数组中是否存在重复元素的方法。通过遍历数组并将每个元素添加到HashSet中,如果某个元素无法添加,则说明该元素已存在于集合中,从而判断数组存在重复。
2504

被折叠的 条评论
为什么被折叠?



