41. 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.

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

1. 思路:

就是把【1,n】範圍內的數歸位,nums數組中大於n的、或者小於等於0的數都不用管


class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0; i < n; i++){
            while(nums[i] > 0 && nums[i] <= n && nums[nums[i]-1] != nums[i]) //只有在【1,n】範圍中的數會歸位
                swap(nums[nums[i] - 1], nums[i]);
        }
        
        for(int i = 0; i < n; i++){
            if(nums[i] != i+1)
                return i+1;
        }
        
        return n+1;
    }
};


發佈了171 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章