First Missing Positive, leetcode solution, best approach

 Statement-

Given an unsorted integer array nums, find the smallest missing positive integer.

Constraints O(n) time and constant extra space.

Input: nums = [3,4,-1,1]
Output: 2


Solution-


class Solution {

public:

    int firstMissingPositive(vector<int>& nums) {

        int n = nums.size();

       int ar[400];

        memset(ar, 0, sizeof(ar));

       for(int i = 0; i < n; i++)

        {

            if(nums[i] > 0 && nums[i] < 301)

                ar[nums[i]]++;

        }

        int ans = 1;

        for(int i = 1; i < 301; i++)

        {

            if(ar[i] == 0)

            {

                ans = i;

                break;

            }

        }

         return ans;

    }

};

Reactions

Post a Comment

0 Comments