Easy to understand 8-line O(n) time O(1) space C++ solution


  • 2
    Z

    class Solution {
    public:

    int missingNumber(vector<int>& nums) {
        nums.push_back(-1);
        for (int i = 0 ;i < nums.size(); i++)
            while (i != nums[i] && nums[i] != -1)
                swap(nums[i], nums[nums[i]]);
        for (int i = 0; i < nums.size(); i++)
            if (nums[i] == -1)
                return i;
        return -1;
    }
    

    };


  • 0
    F

    Great! Sort first and return.


Log in to reply
 

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