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

First Missing Positive

时间:2016-04-09 23:22:29      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Subscribe to see which companies asked this question

大概意思:找出第一个缺失的正整数,

由题意缺失正整数n,只能1<= n <=nums.size()+1,所以可以通过类似hash的方式,将nums的值与下标进行映射,最终让正整数部分有序。

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

 

First Missing Positive

标签:

原文地址:http://www.cnblogs.com/wqkant/p/5372824.html

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