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.
Solution:
Can use hashmap to count frequence of each element.
O(n)
public boolean containsDuplicate(int[] nums) {
int len = nums.length;
if(len <= 1) return false;
Map<Integer, Integer> count = new HashMap<>();
for(int i = 0;i < len; i++) {
if(count.containsKey(nums[i])) {
if(count.get(nums[i]) == 1) return true;
}
count.put(nums[i], 1);
}
return false;
}

本文介绍了一种使用哈希映射来快速判断数组中是否存在重复元素的方法,复杂度为O(n)。
758

被折叠的 条评论
为什么被折叠?



