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.
思路:n个数,可能的最大正整数是n,所以可以将这n个数作为哈希值。但是这样要有O(n)的额外空间。
解决方法是复用A[], 首先将A[i]中的负数剔出(标记为n+1);其次当遍历到一个整数cur的时候,将A[cur]变成相反数,这样A[i]<0的i位置表示i出现过了,还保证了A[i]原来的值没被破坏(可以通过abs(A[i])获得。
class Solution { public: int firstMissingPositive(int A[], int n) { int i; for (i = 0; i < n; i++) if(A[i]<=0) A[i] = n+1; for (i = 0; i < n; i++) { if(abs(A[i]) <= n ){ //需要abs,因为在for循环中,我们将值为[1,n]的元素改成了负数 int cur = abs(A[i])-1; A[cur] = -abs(A[cur]); } } for (i = 0; i < n; i++) { if (A[i] > 0) return i+1; } return n+1; } };
41. First Missing Positive (Map)
原文:http://www.cnblogs.com/qionglouyuyu/p/4854945.html