题目描述:
给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。
你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。
解题思路:
思路1:HashMap
我们先创建一个ArrayList集合和和HashMap集合,将数组中的元素作为键,索引作为值依次存入HashMap中,若已经存在与集合中则将该元素添加到ArrayList集合中。
代码
class Solution {
//HashMap
//Time Complexity: O(N)
//Space Complexit: O(M) M为重复元素的个数
public List<Integer> findDuplicates(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> res = new ArrayList<>();
//若nums长度小于等于1,则直接返回空数组
if (nums.length <= 1) {
return new ArrayList<>();
}
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
res.add(nums[i]);
} else {
map.put(nums[i],i);
}
}
return res;
}
}
思路二:排序法
由于题目中给的元素范围是1-n,所以若我们对元素升序排序后,重复的元素就会相邻,此时我们再遍历数组判断若相邻的元素相等则将其添加到事先创建的ArrayList集合中
代码:
class Solution {
//Sorts
//Time Complexity: O(NlogN)
//Space Complexity: O(M) M为重复元素的个数
public static List<Integer> findDuplicates(int[] nums) {
//对原数组升序排序
Arrays.sort(nums);
List<Integer> res = new ArrayList<>();
if (nums.length <= 1) {
return new ArrayList<>();
}
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i-1]) {
res.add(nums[i]);
}
}
return res;
}
}