O(N) Time Constant Space Clear C++ Solution


  • 0
    C
    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) { 
            int len = nums.size();
            for(int i=0; i<len; ++i){
                if(nums[i]==i+1)
                    continue;
                while(nums[i]!=i+1&&nums[i]>0&&nums[i]<nums.size()&&nums[i]!=nums[nums[i]-1]){ 
                //swap until the invalid solution, ensure the number in the right position
                //caution the duplicate 
                    swap(nums[i],nums[nums[i]-1]);
                }
            }
            int i;
            for(i=0; i<len; ++i){ //find the first no match number
                if(nums[i]!=i+1)
                    break;
            }
            return i+1;
        }
        void swap(int &a,int &b){
            int temp = a;
            a = b;
            b = temp;
        }
    };

  • 0
    Z

    Thanks a lot


Log in to reply
 

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