一、问题描述
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.
二、问题分析
题目没有对空间的要求,因此最简单的方式,unique与set恰好对应,因此可以使用hashset来判重。
三、Java AC代码
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> container = new HashSet<Integer>();
if (nums==null || nums.length==0) {
return false;
}
int len = nums.length;
for(int i=0;i<len;i++){
if (!container.contains(nums[i])) {
container.add(nums[i]);
}else {
return true;
}
}
return false;
}