15.存在重复元素
一、题目
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
链接:https://leetcode-cn.com/problems/contains-duplicate/solution/cun-zai-zhong-fu-yuan-su-by-leetcode-sol-iedd/
来源:力扣(LeetCode)
二、示例
示例①
输入: [1,2,3,1]
输出: true
示例②
输入: [1,2,3,4]
输出: false
三、代码实现
public static boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> hashmap = new HashMap<Integer, Integer>();
for (int i = 0;i < nums.length;i++){
if (hashmap.containsValue(nums[i])){
return true;
}else {
hashmap.put(i,nums[i]);
}
}
return false;
}
测试后能行,就是搞不懂为什么超出时间限制,明明只有一个循环
方法一:排序
public static boolean containsDuplicateBySort(int[] nums){
Arrays.sort(nums);
int n = nums.length;
for (int i = 0;i < n - 1;i++){
if (nums[i] == nums[i+1]){
return true;
}
}
return false;
}
这个应该也是差点超出时间限制,sort有个循环,外面有层循环,这个过了为什么我那个没过-_-
方法二:哈希表
public static boolean containDuplicateBySet(int[] nums){
HashSet<Integer> integers = new HashSet<>();
for (int num : nums){
if (!integers.add(num)){
return true;
}
}
return false;
}
算是最好的方法,评论里的方法懒得找了,耗时一般,
四、复杂度分析
排序
- 时间复杂度O(NlogN)
- 空间复杂度O(logN)
哈希表
- 时间复杂度O(N)
- 空间复杂度O(N)