哈希表系列一>存在重复元素II 存在重复元素I
目录
- 题目:
- 解析:
- 存在重复元素 II-->代码:
- 存在重复元素-->代码:
题目:
链接: link
链接: link
解析:
存在重复元素 II–>代码:
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer> hash = new HashMap<>();//<nums[i],i>
for(int i = 0; i < nums.length; i++){
if(hash.containsKey(nums[i])){
if(i - hash.get(nums[i]) <= k) return true;
}
hash.put(nums[i],i);
}
return false;
}
}
存在重复元素–>代码:
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> hash = new HashSet<>();
for(Integer x : nums){
if(hash.contains(x))
return true;
hash.add(x);
}
return false;
}
}