class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int x : nums) {
if (!set.add(x)) {
return true;
}
}
return false;
}
}
Set<Integer> set = new HashSet<Integer>();是用来创建哈希表的
for (int x : nums)
是一个for each循环。遍历数组这个是JAVA 5以后才有的新特性。也可以这么写;
if (!set.add(x))
在执行add方法时候,如果这个元素已经在set中存在,那么就返回false,否则返回true。
所以,我们可以根据返回值,来确定当前添加的元素是否已经在set中存在。