First Missing Positive

来源:互联网 发布:网络受到攻击 编辑:程序博客网 时间:2024/05/16 13:56

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.


//http://www.cnblogs.com/ganganloveu/p/4164834.htmlclass Solution {public:    int firstMissingPositive(vector<int>& nums) {                int n = nums.size();        if(n == 0)            return 1;        sort(nums.begin(),nums.end());        int i = 0;        while(i < n && nums[i] <= 0)            i ++;        if(i == n)            return 1;        int tag = 1;        for(; i < n; i ++)        {            if(nums[i] > tag)            //miss the tag                return tag;            else if(nums[i] == tag)            //next positive                tag ++;            else                ;        }        //i==n, miss the tag        return tag;            }};



0 0
原创粉丝点击