【LeetCode篇】 41. First Missing Positive

【LeetCode篇】 First Missing Positive


  • IDE: C++ (C)
  • author : MinRam
  • create : 03/19/2019
  • update: 03/19/2019

題目

First Missing Positive - LeetCodeios

  • Given an unsorted integer array, find the smallest missing positive integer.
  • Your algorithm should run in O(n) time and uses constant extra space.

思路

大致思路,簡易桶。 直接以值爲Key,發散到數組中,經過Swap實現。數組

僞代碼優化

  1. 判斷Current是否知足一下狀況,若知足則2,反之3ui

    • 正數
    • 小於答案的最大值 $(所求的正數 \leq 數組長度)$
  2. CurrentNum[Current - 1] 交換。
  3. 下一位,重複1,直到數組遍歷結束。

圖片流
步驟圖spa

代碼實現

// 優化io流
static const auto __ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int numsLen = nums.size(); 
        // 簡易桶
        for (int i = 0 ; i < numsLen; ){
            if (nums[i] != (i + 1) && nums[i] >= 1 && nums[i] <= numsLen && nums[nums[i] - 1] != nums[i])
                swap(nums[i], nums[nums[i] - 1]);
            else
                ++i;
        }
        // 遍歷查值
        for (int i = 0; i < numsLen; ++i)
            if (nums[i] != (i + 1))
                return i + 1;
        // 最大值
        return numsLen + 1;
    }
};

參考

[1] Longest palindromic substring - LeetCodecode

反饋與建議

相關文章
相關標籤/搜索