First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
return3
,
and[3,4,-1,1]
return2
.Your algorithm should run in O(n) time and uses constant space.
题目意思:
返回第一个缺失的正数。
时间复杂度应该在O(n)且只能使用常数的额外空间。
解题思路:
遍历两遍数组,第一遍的目的是使数组下标为 i 的数值设置为 i+1,如没有 i+1 就是其他值(不在1~n范围的值)。
第二遍遍历的目的是返回第一个不满足下标为 i ,值为 i+1 的地方,return i + 1;
代码如下:
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 int i = 0; 5 while(i < n){ 6 if(A[i] != i+1 && A[i]>0 && A[i]<=n && A[A[i]-1] != A[i]) 7 swap(A[i],A[A[i]-1]); 8 else 9 i++; 10 } 11 for(i = 0; i < n; i++){ 12 if(A[i] != (i+1)) 13 return i+1; 14 } 15 return n+1; 16 } 17 };