448. Find All Numbers Disappeared in an Array

1. 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.

2. Example

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

3. Solutions

My Accepted Solution(Follow Up)

n = m_nums.size()
Time complexity: O(n)
Space complexity: O(1)

// we put every number to its position, which is its value minue one
// then, duplicate number will be placed at positions belonged to missing numbers

class Solution 
{
public:
    // vector<int> findDisappearedNumbers(vector<int>& nums)
    vector<int> findDisappearedNumbers(vector<int> &m_nums) 
    { 
        for(int i = 0; i < m_nums.size(); i++)
        {
            while(m_nums[i] != i + 1 && m_nums[m_nums[i] - 1] != m_nums[i])
            {
                swap(m_nums[i], m_nums[m_nums[i] - 1]);
            }
            
        }
     
        vector<int> result;
        for(int i = 0; i < m_nums.size(); i++)
        {
            if(m_nums[i] != i + 1)
            {
                result.push_back(i + 1);
            }
        }
        
        return result;
    }
};

3.1 Convert Numbers to Negative(Follow Up)

n = m_nums.size()
Time complexity: O(n)
Space complexity: O(1)

// all numbers in m_nums are non negative
// when we iterate numbers, we put the number, which with current value minus one as index, to negative
// so the index whose number is positive is the number missing

class Solution 
{
public:
    // vector<int> findDisappearedNumbers(vector<int>& nums)
    vector<int> findDisappearedNumbers(vector<int> &m_nums)  
    {
        for(int i = 0; i < m_nums.size(); i++)
        {
            int index = abs(m_nums[i]) - 1;
            
            m_nums[index] = -abs(m_nums[index]);
        }
        
        vector<int> result;
        for(int i = 0; i < m_nums.size(); i++)
        {
            if(m_nums[i] > 0)
            {
                result.push_back(i + 1);
            }
        }
        
        return result;
    }
};
Last updated:
Tags: Array
comments powered by Disqus