您的位置:首页 > 其它

LeetCode 40 First Missing Positive

2014-06-18 14:21 141 查看
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.

先排序,再检查,交换

class Solution {
public:
	int firstMissingPositive(int A[], int n) {
		sort(A, A+n);
		int res = 0;
		int i = 0;
		while (i<n && A[i]<=0) i++;
		for (; i < n; i++)
		{//注意:一看到序列就应该马上反应问题:是否有重复元素???
			if (i>0 && A[i] == A[i-1]) continue;
			if (A[i] - res != 1) return res+1;
			else res = A[i];
		}
		return res+1;
	}
};


或者,先交换排序,后检查

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        int i = 0;
        while (i < n)
        {
            if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i])
                swap(A[i], A[A[i]-1]);
            else
                i++;
        }
        for (i = 0; i < n; ++i)
            if (A[i] != (i+1))
                return i+1;
        return n+1;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: