/*
* 存在重复元素
* 给定一个整数数组,判断是否存在重复元素。
* 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
* 输入: [1,2,3,1] 输出: true
* 输入: [1,2,3,4] 输出: false
* 输入: [1,1,1,3,3,4,3,2,4,2] 输出: true
*/
public class LeetCode217 {
public boolean containsDuplicate(int[] nums) {
Set<Integer> hashSet = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if (hashSet.contains(nums[i])){
return true;
}
hashSet.add(nums[i]);
}
return false;
}
}
测试及结果
@Test
public void testLeetCode217() {
LeetCode217 leetCode217 = new LeetCode217();
int[] arr = {1,2,3,4};
System.out.println(leetCode217.containsDuplicate(arr));
}
//结果
//false