Find All Numbers Disappeared in an Array

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

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

Example:

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

Output:
[5,6]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intfindDisappearedNumbers(vector<int&nums)
{
    sort(nums.begin(), nums.end());
    vector<intres;
    set<intst;
    for (int i = 0i < nums.size(); i++)
        st.insert(nums[i]);
    for (int i = 1i <= nums.size(); i++)
        if (st.find(i== st.end())
            res.push_back(i);
    return res;
}

int main()
{
    vector<intnums = {43278231};

    vector<intres = findDisappearedNumbers(nums);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment