Q:
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:
雖然不能再另外開辟非常數級的額外空間,但是可以在輸入數組上就地進行swap操作。
思路:交換數組元素,使得數組中第i位存放數值(i+1)。最后遍歷數組,尋找第一個不符合此要求的元素,返回其下標。整個過程需要遍歷兩次數組,復雜度為O(n)。
下圖以題目中給出的第二個例子為例,講解操作過程。
最后,具體實現如下:
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 int i = 0; 5 while (i < n) 6 { 7 if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i]) 8 swap(A[i], A[A[i]-1]); 9 else 10 i++; 11 } 12 for (i = 0; i < n; ++i) 13 if (A[i] != (i+1)) 14 return i+1; 15 return n+1; 16 } 17 };
原創文章,轉載請注明出處:http://www.cnblogs.com/AnnieKim/。