问题描述:
检测一个数组中是否含有相同元素
解决:因为set中不可添加重复元素的特性,我们可以用set来保存遍历过的元素,一旦set添加新元素失败,表明新元素与已有元素重复。
/*
* 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.
*/
import java.util.HashSet;
import java.util.Set;
public class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
if(nums == null||nums.length==0)
return false;
Set<Integer> set = new HashSet<Integer>();
for(int i:nums) {
if(!set.add(i))
return true;
}
return false;
}
}