217. 存在重复元素
题目描述
解题思路
第一种思路:
先对nums数组排序,然后再在遍历nums,如果nums[i] == nums[i + 1],则返回true。
第二种思路:
利用Set集合的性质(不存储相同值),遍历一次nums集合并set.add(),如果add失败,则存在相同元素,返回true。
这里是Set系列集合的源码分析:【攻克java集合系列(三)】java集合中的Set系列集合全面分析
代码实现
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int num:nums){
if(!set.add(num)){
return true;
}
}
return false;
// 以下为思路一:
// Arrays.sort(nums);
// int length = nums.length;
// for (int i = 0; i < length - 1; i++) {
// if (nums[i] == nums[i + 1]) {
// return true;
// }
// }
// return false;
}
}