给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。
    你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。
    示例 1:
    输入:nums = [4,3,2,7,8,2,3,1]
    输出:[2,3]
    示例 2:

    输入:nums = [1,1,2]
    输出:[1]
    示例 3:

    输入:nums = [1]
    输出:[]

    1. /**
    2. * @param {number[]} nums
    3. * @return {number[]}
    4. * 思路:
    5. * 空间交换时间
    6. * 1、使用hash记录出现过的元素
    7. * 2、若再hash中存在,push进入结果数组res
    8. *
    9. * 时间复杂度:O(N), 空间复杂度:O(N)
    10. */
    11. var findDuplicates = function (nums) {
    12. let res = []
    13. let setHash = new Set()
    14. for (let i = 0; i < nums.length; i += 1) {
    15. if (setHash.has(nums[i])) {
    16. res.push(nums[i])
    17. } else {
    18. setHash.add(nums[i])
    19. }
    20. }
    21. return res
    22. };

    时间复杂度o(n) 空间复杂度 o(n)
    image.png