[Leetcode] First Missing Positive

First Missing Positive

Given an unsorted integer array, find the first missing positive integer.數組

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.spa

Your algorithm should run in O(n) time and uses constant space.code

數組哈希法

複雜度

O(N) 時間 O(1) 空間it

思路

這道題先得理解深入,再作
對於一個數組,長度爲n,咱們在最後返回的答案確定是[1,n+1]閉區間範圍內,超出這個區間不多是答案,跳過便可
咱們要作的就是,兩步走:
1.把數組中有多是答案的數([1,n+1]閉區間內的數)放在正確的位置上:num放在下標爲num-1的位置上,好比4放在下標爲3的位置上,注意有多是答案的數才放,此時不會數組越界。
2.最後在這些可能的位置上找答案,這些位置是0到n-1。
舉幾個例子:
[5,6,7],答案:1
[5],答案:1
[-5],答案:1
[0],答案:1
[1],答案:2
[2,2],答案:1
注意最後這個例子,對於第一個2,這個數在答案區間內,但是咱們發如今他應該出現的位置上已是他了,那麼咱們視當前這個位置的2不是答案,跳過這個。這個特例須要注意喲~io

注意

注意[2,2]這種狀況喲class

代碼

public class Solution {
    public int firstMissingPositive(int[] nums) {
        for (int i = 0; i < nums.length; ) {
            int n = nums[i];
            if (n >= 1 && n <= nums.length + 1 && nums[n - 1] != n) {//這個數在答案區間
                int tmp = nums[n - 1];
                nums[n - 1] = n;
                nums[i] = tmp;
            } else {    //不在答案區間跳過無論
                i++;
            }
        }
        for (int i = 1; i < 1 + nums.length; i++) {
            if (nums[i - 1] != i)
                return i;
        }
        return nums.length + 1;
    }
}
相關文章
相關標籤/搜索