题目
给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。
找到所有出现两次的元素。
你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?
示例
输入:
[4,3,2,7,8,2,3,1]
输出:
[2,3]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:模拟
Python实现
利用counter来计数
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
counter = collections.Counter()
out = list()
for num in nums:
counter[num] += 1
for k, v in counter.items():
if v == 2:
out.append(k)
out.sort()
return out
Java实现:HashSet
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) res.add(num);
}
return res;
}
}
方法2:鸽笼法
Java实现
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
int idx = Math.abs(nums[i]) - 1;
if (nums[idx] > 0) nums[idx] *= -1;
else {
res.add(idx + 1);
}
}
return res;
}
}