leetcode 41缺失的第一个正数

time O(n) space O(1)

 

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        //从1开始将范围内的整数交换到对应的位置
        int len=nums.size();
        int res=1;
        
        for(int i=0;i<len;i++){
            int x=i;
            /*//show every state before swap
            cout<<"nums["<<i<<"]: "<<endl;
            for(int j=0;j<len;j++)
                cout<<nums[j]<<",";
                cout<<endl;*/
            while(nums[x]>0 && nums[x]<len && nums[x]!=nums[nums[x]-1]){
                swap(nums[x],nums[nums[x]-1]);
                /*//show every swap result
                for(int j=0;j<len;j++)
                    cout<<nums[j]<<",";
                cout<<endl;*/
            }
                
            
        }
        for(int i=0;i<len;i++){
            if(nums[i]!=i+1) break;
            res++;
        }
        return res;
    }
};
posted @ 2019-06-12 16:07  Joel_Wang  阅读(116)  评论(0编辑  收藏  举报