First Missing Positive 分类: Leetcode(排序) 2015-04-09 17:13 25人阅读 评论(0) 收藏
First Missing Positive
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.
想出这个算法的真是大神,首先,他简化了这个问题,这个问题其实与负数一点关系没有,其次,他充分利用了数组这个结构,真是一点都没有浪费。
其实思想简单,但是想到不简单,就是把(A[i])5与A[4](A[A[i]-1])交换,这样其实是找到了一种映射。
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for ( int i = 0 ; i < n; i++) {
while(A[i] > 0 && A[i] <= n && A[A[i-1]] !=A[i])
swap(A[i], A[A[i]-1]);
}
for( int i = 0; i < n; ++i) {
if (A[i] != i+1)
return i+1;
}
return n+1;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

浙公网安备 33010602011771号