C++ O(N) Time O(1) Space, 122ms Beats 97%


  • 0
    M

    We use 30th bit of numbers in array to mark numbers that exist in array. After that we output numbers without mark. Thus no extra space is used.

    class Solution {
    public:
        vector<int> findDisappearedNumbers(vector<int>& nums) {
            for (int n: nums) nums[(n & ((1 << 30) - 1)) - 1] |= 1 << 30;
            vector<int> result;
            for (int i = 0; i < nums.size(); ++i) if ((nums[i] >> 30) == 0) result.push_back(i + 1);
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.