(Js) Leetcode 442. Repeated data in the array

topic:

Given an integer array a, where 1 ≤ a[i] ≤ n (n is the length of the array), some elements appear twice while others appear once.

Find all elements that appear twice.

Can you solve this problem in O(n) time without using any extra space?

Example:

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

Output:
[2,3]

Ideas:

Use the positive and negative of the number in the array to indicate whether the number corresponding to the position has already appeared

Code:

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findDuplicates = function(nums) {
    let res = [];
    for(let i = 0; i < nums.length; i++) {
        let num = Math.abs(nums[i]);
        if(nums[num - 1] > 0) {
            nums[num - 1] *= -1;
        } else {
            res.push(num);
        }
    }
    return res;
};

operation result:

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113889291