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]放到A[A[i]]位置去,也就是所有正数和其下标对应起来。然后扫描数组,找到第一个不对应的。
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 5 int i=0; 6 while(i<n) 7 { 8 if(A[i]>0&&A[i]<n&&A[A[i]-1]!=A[i]) 9 { 10 swap(A[i],A[A[i]-1]); 11 }else i++; 12 } 13 14 for(int k=0;k<n;k++) 15 { 16 if(A[k]!=k+1) 17 return k+1; 18 } 19 return n+1; 20 } 21 };
A:
虽然不能再另外开辟非常数级的额外空间,但是可以在输入数组上就地进行swap操作。
思路:交换数组元素,使得数组中第i位存放数值(i+1)。最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)。
下图以题目中给出的第二个例子为例,讲解操作过程。

浙公网安备 33010602011771号