Swift Solution - O(n) time


  • 0
    class Solution {
        func firstMissingPositive(_ nums: [Int]) -> Int {
            if nums.count == 0 {
                return 1
            }
            
            var nums = nums
            
            for i in 0..<nums.count {
                while nums[i] >= 1 && nums[i] <= nums.count && nums[nums[i] - 1] != nums[i] {
                    swap(&nums[i], &nums[nums[i] - 1])
                }
            }
            
            for i in 0..<nums.count {
                if nums[i] != i + 1 {
                    return i + 1
                }
            }
            
            return nums.count + 1
        }
    }
    

Log in to reply
 

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