您的位置:首页 > 其它

LeetCode_First Missing Positive

2013-05-24 23:36 429 查看
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://blog.unieagle.net/2012/09/20/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Afirst-missing-positive/

class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int outOfRange = n + 2;
for(int i = 0; i< n; i++)
if(A[i]<=0)
A[i] = outOfRange ;
int absi;
for(int i = 0; i< n; i++)
{
absi = abs(A[i]);
if(absi <= n)
{
A[absi-1] = -abs(A[absi-1]) ;
}
}

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