码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 41. First Missing Positive

时间:2017-10-02 23:10:34      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:should   bre   first   vector   ant   最大的   https   log   miss   

link

 

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.

 

题意: 给定一个数组,返回不在数组中的最小的正整数。

要求O(n)的复杂度和O(1)的空间复杂度。

思路:

首先明显有:答案不会大于数组的长度+1。 (最大的情况是所有的数是从1-n的一个排列,则结果为n+1)。

为了在O(n)的时间中求出答案,我们理论上本来可以使用一个数组bool app[i]来表示i + 1是否出现,并且只保留1-n的数(原因如上述,答案不会超过n+1)。在O(N)的时间处理完以后,再从0 ~ n-1看app[i]是否为true。

现在要求空间也为常数,则我们考虑利用原数组进行上面的事情。

遍历一次数组,若nums[i]不为正数或者大于数组长度,则无视这些值。对于nums[i]-1 > i的i(也就是,要修改未来遍历的值),我们交换i和nums[i]-1 两个位置(这都是下标)的数,直到本条件不满足。

 

注意: 

1. 为什么要交换 : 因为不能确定nums[nums[i]-1 ]是否也会修改之后遍历的位置。

2. 判定条件要加一个nums[i] != nums[nums[i]-1]  否则对于[2,2]这种情况会陷入循环。

 

code:

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        
        int len = nums.size();
        if(len == 0) return 1;
        for(int i = 0; i < len; i++){
            if(nums[i] <= 0 || nums[i] > len) continue;
            // put 1 - > 0, so put nums[i] to nums[i] - 1
            while(nums[i] - 1 > i && nums[nums[i]-1] != nums[i]){
                // will change element in it‘s right side 
                int tp = nums[nums[i] - 1];
                nums[nums[i] - 1] = nums[i];
                if(tp <= 0 || tp > len) break;
                nums[i] = tp;
            }
            nums[nums[i] - 1] = nums[i];
            
        }
        for(int i = 0; i < len; i++){
            if(nums[i] != i + 1) return i+1;
        }
        return len + 1;
    }
};

 

leetcode 41. First Missing Positive

标签:should   bre   first   vector   ant   最大的   https   log   miss   

原文地址:http://www.cnblogs.com/bbbbbq/p/7622822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!