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 個正數是 1~n,那麼存在兩種情況:
1. 數組中正好包含了 1~n 這 n 個數,此時缺失的最小正數爲 n+1;
2. 數組中包含了 1~n 這個範圍外的數,那麼缺失的最小正數必然是在 1~n 這個範圍裏。
如此,我們只需要關注 1~n 這 n 個數是否出現就行。使用查找表的思想,得到一個空間複雜度O(n),時間複雜度O(n)的算法,實現代碼如下:
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) {
return 1;
}
// 創建一個查找表,用來記錄 1~nums.length 中數字的出現情況
boolean[] exist = new boolean[nums.length];
for (int i=0; i<nums.length; i++) {
if (nums[i] <= nums.length && nums[i] > 0) {
exist[nums[i]-1] = true;
}
}
// 數組中缺失了 1~nums.length 範圍內的數
for (int i=0; i<nums.length; i++) {
if (!exist[i]) {
return i+1;
}
}
// 數組中包含了 1~nums.length
return nums.length+1;
}
}
當然也可以直接在原數組上進行操作,將數轉移到對應的位置上,得到一個空間複雜度O(1)的算法,具體實現並不複雜,衆位看官可以動手試試。
作業部落鏈接