Alternate Solution without using Swap C++ O(n) space O(1) complexity


  • 0
    B

    The basic idea is to replace all nums[i]<=0 with nums.size()+1.
    Now the problem reduces to finding first missing positive with only positive numbers in the array.

    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            int n = nums.size();
            
            for(int i = 0; i < n; i++) if(nums[i]<=0) nums[i] = n + 1;
            for(int i = 0; i < n; i++) {
                int pos = nums[i];
                if(pos < 0) pos *= -1;
                if(pos > 0 && pos <= n && nums[pos - 1] > 0) nums[pos - 1] *= -1;
            }
            for(int i = 0; i < n; i++) if(nums[i] > 0) return i+1;
            return n+1;
        }
    };
    
    

Log in to reply
 

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