Question:

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]

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[]}
  4. */
  5. var findDuplicates = function(nums) {
  6. let result = [];
  7. let map = {};
  8. // 循环 O(n).
  9. for (let i = 0; i < nums.length; i++) {
  10. if (!map[nums[i]]) {
  11. map[nums[i]] = 0
  12. }
  13. map[nums[i]]++;
  14. }
  15. for (let j in map) {
  16. if (map[j] > 1) {
  17. result.push(j);
  18. }
  19. }
  20. return result;
  21. };

Runtime: 156 ms, faster than 36.36% of JavaScript online submissions for Find All Duplicates in an Array.