题目

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

  1. Input:
  2. [4,3,2,7,8,2,3,1]
  3. Output:
  4. [2,3]

题意

给定一个长度为n的数组,其中元素的值域为1-n,求重复元素的集合,要求时间复杂度为0442. Find All Duplicates in an Array (M) - 图1,空间复杂度为0442. Find All Duplicates in an Array (M) - 图2

思路

第一次遍历,重排元素使得尽可能满足0442. Find All Duplicates in an Array (M) - 图3;第二次遍历,找到左右不满足0442. Find All Duplicates in an Array (M) - 图4的元素,这些就是重复元素。


代码实现

Java

  1. class Solution {
  2. public List<Integer> findDuplicates(int[] nums) {
  3. List<Integer> list = new ArrayList<>();
  4. int i = 0;
  5. while (i < nums.length) {
  6. int j = nums[i] - 1;
  7. if (nums[i] != nums[j]) {
  8. int tmp = nums[i];
  9. nums[i] = nums[j];
  10. nums[j] = tmp;
  11. } else {
  12. i++;
  13. }
  14. }
  15. i = 0;
  16. while (i < nums.length) {
  17. if (nums[i] != i + 1) {
  18. list.add(nums[i]);
  19. }
  20. i++;
  21. }
  22. return list;
  23. }
  24. }