sharing my c++ solution


  • 0
    B
    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            int n = nums.size(), maxval = INT_MIN;
            if(n==0) return 1;
            for(int num:nums) maxval = max(num,maxval);
            int head = 0, tail = n-1;
            while(head<tail) {
                if(nums[head]<=0 && nums[tail]>0) {
                    swap(nums[head],nums[tail]);
                    nums[tail]=0;
                    head++;
                    tail--;
                }
                else if(nums[head]<=0 && nums[tail]<=0) {nums[tail]=0;tail--;}
                else if(nums[head]>0 && nums[tail]>0) head++;
                else if(nums[head]>0 && nums[tail]<=0) {nums[tail]=0;head++,tail--;}
            }
            nums[head] = (nums[head]<0)?0:nums[head];
            for(int k = 0; k < nums.size(); k++) {
                if(nums[k]==0) continue;
                nums[abs(nums[k])-1] = -abs(nums[abs(nums[k])-1]);
            }
            for(int k = 0; k < nums.size(); k++) if(nums[k]>=0) return k+1;
            return maxval+1;
        }
    };
    

Log in to reply
 

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