注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
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.
代码1:先排序,时间复杂度O(nlogn),(若不考虑排序所用空间复杂度)空间复杂度O(1)
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i ++) {
if (nums[i] == nums[i + 1]) return true;
}
return false;
}
}
代码2:使用HashSet, 时间复杂度O(n),空间复杂度O(n)
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> hasDups = new HashSet<>();
for (int i = 0; i < nums.length; i ++) {
if (hasDups.add(nums[i]) == false)
return true;
}
return false;
}
}
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int i : nums) {
if (set.contains(i)) return true;
set.add(i);
}
return false;
}
}

本文介绍两种检测整型数组中是否存在重复元素的方法:一种通过排序实现,时间复杂度为O(nlogn);另一种利用HashSet数据结构,实现O(n)的时间复杂度。这两种方法各有优劣,适用于不同场景。

4567

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



