Leetcode 41. First Missing Positive

@author stormma
@date 2017/11/30


生命不息,奮鬥不止!


題目

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.

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

題目分析

題目意思很好理解,找到第一個缺失的整數,對於樣例1來說 [1, 2, 0]缺3,樣例2 => [1, -1, 3, 4]缺失的是2。

我們通過重新hash元素應在的位置來找出缺失的整數。怎麼重新hash元素的位置呢?我們這樣定義:

nums[nums[i] - 1] = i
這個是什麼意思呢?

很顯然,我們用index = 0來存儲整數1,index = 1來存儲整數2,這樣答案就很簡單了,如果我們沒有找到nums[i] != i + 1的i,那麼就直接返回len + 1即可。爲什麼?比如[1, 2, 3, 4]我們應該返回5。

代碼實現

class Solution {
    public int firstMissingPositive(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] != nums[i]) {
                swap(nums, nums[i] - 1, i);
            }
        }

        // find ans
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                return i +1;
            }
        }
        return nums.length + 1;
    }
    // [3, 4, -1, 1]
    // [-1, 4, 3, 1]
    // [-1, 1, 3, 4]
    // [1, -1, 3, 4]
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章