題目:
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.
思路1:Bit Manipulation 受之前一道題目的啓發Contains Duplicate(217)
用一個byte數組作爲標記位,每個byte可以標記8個數字。遍歷nums,並標記出現的正整數,然後從低位開始判斷,第一個缺少的正整數。
同樣這種方法存在缺陷就是byte數組的長度:按理應該是(2^32)/8
代碼1:
public int firstMissingPositive(int[] nums) {
byte[] mark = new byte[150000];
mark[0]|=1;//set 0 mark,方便後續分析
for(int i : nums){
if(i>0){
int byteBlock = i/8;//確定i在第幾個byte裏面
int byteIndex = i%8;//確定i在byte中具體的位置
mark[byteBlock]|=1<<byteIndex;//把i在byte[]中的標記位設置1
}
}
for(int i=0;i<mark.length;i++){
if(mark[i]!=255){ //如果爲255,說明btye中標記位全部爲1,如果不是255,說明存在0
for(int j=0;j<=7;j++){
if(mark[i]!=(mark[i]|(1<<j))){//找到具體的低位的0
return (j+8*i);
}
}
}
}
return -1;
}
思路2:從leetcode上看到的。把讀取到的正整數放到對應的位置
【3,4,-1,1】=>【1,-1,3,4】 然後找到第一個不對應的元素即可。
見leetcode鏈接:https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time
代碼2:
class Solution
{
public:
int firstMissingPositive(int A[], int n)
{
for(int i = 0; i < n; ++ i)
while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
swap(A[i], A[A[i] - 1]);
for(int i = 0; i < n; ++ i)
if(A[i] != i + 1)
return i + 1;
return n + 1;
}
};