Post

Leetcode - 41. First Missing Positive

Leetcode - 41. First Missing Positive

Hits

  • Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.

    You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.

Solution

n will always belong to [1...len(nums)+1] inclusive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func firstMissingPositive(nums []int) int {
    i:=0

    // Rearrange the elements to place each positive integer at its correct index.
    // Negative numbers and numbers greater than the array size are ignored.
    for i < len(nums) {
        if nums[i]>0 && nums[i]<len(nums) && nums[i]!=nums[nums[i]-1] {
            nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
        }else{
            i++
        }
    }
    fmt.Println(nums)

    for i:=0; i<len(nums); i++{
        if nums[i] != i+1{
            return i+1
        }
    }

    return len(nums)+1
}
This post is licensed under CC BY 4.0 by the author.