448. Find All Numbers Disappeared in an Array

Description

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

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

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

Solution

Solution 1

/**
 * Solved with hash table
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
    "use strict";
    let table = [];
    for (let i = 0; i < nums.length; i++) {
        if (!table[nums[i]]) {
            table[nums[i]] = 1;
        } else {
            table[nums[i]]++;
        }
    }
    let result = [];
    for (let i = 1; i <= nums.length; i++) {
        if (!table[i]) {
            result.push(i);
        }
    }
    return result;
};

Solution 2

/**
 * No extra space needed
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
    "use strict";
    for (let i = 0; i < nums.length; i++) {
        let idx = nums[i] > 0 ? nums[i]-1 : (-nums[i])-1;
        // Mark corresponding index of a visited element as negative
        if (nums[idx] > 0) {
            nums[idx] = -nums[idx];
        }
    }
    let result = [];
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] > 0) {
            result.push(i+1);
        }
    }
    return result;
};

results matching ""

    No results matching ""