您的位置:首页 > 其它

【LeetCode】First Missing Positive

2014-06-11 11:05 405 查看
题目描述:

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(n*logn),不符合条件。因此考虑用别的什么方法实现排序。
观察下题目发现有两个特点:

1、所求值为正数,这意味着小于等于0的数我们可以忽略掉。

2、最极端的例子1,2,3,4,5……n-1中最大值也是小于n的,这意味着大于等于n的数也可以忽略掉。

由此我们只要对1~n-1之间的数进行排序就好了。要求用常数空间,跟Remove Duplicates from Sorted Array题目类似,用原数组来进行排序,只要将A[i]放置到A[i]-1的位置就好了,即满足上述两个条件时,swap(A[i], A[A[i] - 1])。为了避免无限循环和出现重复项,还需要加个判定条件A[A[i]
- 1] != A[i]。

代码如下:

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