Leetcode442:数组中重复的数据
-
题目:
-
给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。
你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。
-
-
思路:
- 定义一维数组且初始化所有的数据为1,每当数组的数字位置出现过1次,数组的数字位置的值减1;
- 当数组的数字位置的值小于0时,说明数组的数字位置出现过两次或以上次数,则将该数字添加到目标数组。
-
代码如下:
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new LinkedList<>();
int n = nums.length;
int[] numsPlace = new int[n+1];
Arrays.fill(numsPlace,1);
for(int i = 0; i < n; i++){
numsPlace[nums[i]]--;
if(numsPlace[nums[i]]<0){
res.add(nums[i]);
}
}
return res;
}
}