[Leetcode]41.FirstMissingPositive

54 阅读1分钟

Description:

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.

Example 1:

Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.

Solution: Hard|Easy||Positioning Elements at correct index

The above link give us a really key hint. The problem requires finding the smallest positive integer that is not present in an unsorted integer array. We should utilize the fact that the answer lies within the range [1, n+1], where n is the size of the array. So we should rearrange the elements of array to the right place(nums[element - 1]), then find the first index i where nums[i] != i + 1.

fun firstMissingPositive(nums: IntArray): Int {
    // rearrange the array
    for (i in nums.indices) {
        while (nums[i] > 0
            && nums[i] - 1 < nums.size
            && nums[i] != nums[nums[i] - 1] // in case of [2,2,3,3] which lead infinite loop
            && nums[i] != (i + 1)) { // swap the element to correct place
            val temp = nums[i]
            nums[i] = nums[nums[i] - 1]
            nums[temp - 1] = temp // the nums[i] has changed, so use temp
        }
    }
    for (i in nums.indices) {
        if (nums[i] != i + 1) {
            return i + 1
        }
    }
    return nums.size + 1 //the nums contains 1-n, so the next is n + 1
}