题目
判断数组中是否存在重复的元素
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.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
思路1
双层循环,一一比对,时间复杂度O(n^2)
思路2
将数组排序后遍历一次,检查相邻元素是否相等,时间复杂度(nlgn)
思路3
使用HashSet这种数据结构,使得插入和查找操作的复杂度为O(1),遍历数组一次,若元素不重复则插入,重复则直接返回false,时间复杂度为O(n)
代码
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>(nums.length);
for(int num :nums){
if(set.contains(num)) return true;
set.add(num);
}
return false;
}
}
Runtime: 10 ms, faster than 50.95% of Java online submissions for Contains Duplicate.
Memory Usage: 41.6 MB, less than 47.93% of Java online submissions for Contains Duplicate.