Super Easy Accepted Solution.Detailed comments. 11ms. O(n) time & O(1) space.


  • 0
    Y

    The idea is really easy.
    First set answer to be 1, the very first positive number.
    search the array for this "ans". If found, ans increments by 1.
    Till one point that ans is not found, return ans.

    // Time: O(n);
    // space: O(1);
    public class Solution {
        public int firstMissingPositive(int[] nums) {
            // initialize the ans to be the first positive number: 1
            int ans = 1;
            // if ans is found in the array nums.
            while (findNumber(ans,nums)){
                // increment ans to see if the new ans exists
                     ans++;
            }
            return ans;
        }
        
        // helper function to check through the nums to see if target number exists.
        private boolean findNumber(int num,int[] nums){
            // iterate through the array to see if num exists
            for (int n : nums){
                if (n == num){
                    return true;
                }
            }
            return false;
        }
    }
    

  • 0
    Y

    This is O(n2) solution, for each positive number you iterated through the entire array, so it's n * n.


Log in to reply
 

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