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

First Missing Positive

时间:2015-03-10 10:26:23      阅读:136      评论: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.

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct great_zero :public unary_function<int, bool>{
	bool operator()(int&x){ return x > 0; }
};
int firstMissingPositive(int A[], int n) {

	vector<int>T(A, A + n);
	if (T.empty())
		return 1;
	sort(T.begin(), T.end());
	auto iter = find_if(T.begin(), T.end(), great_zero());
	if (iter==T.end())
		return 1;
	int target = *iter;
	if (target > 1)
		return 1;
	for (; iter != T.end(); ++iter)
	{
		if (*iter - target>1)
			return target + 1;
		target = *iter;
	}
	return T.back() + 1;
}


def firstMissingPositive(A):
    if len(A)==0:
        return 1
    A.sort()
    posIdx = None
    target = None
    for index in range(len(A)):
        if A[index]>0:
            posIdx = index
            target = A[index]
            break
    else:
        return 1;
    if target > 1:
        return 1
    for index in range(posIdx+1,len(A)):
        if A[index]-target>1:
            return target+1
    return A[len(A)-1]+1



 

 

First Missing Positive

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/44171523

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