給定一個未排序的整數數組,找出其中沒有出現的最小的正整數。
示例 1:
輸入: [1,2,0]
輸出: 3
示例 2:
輸入: [3,4,-1,1]
輸出: 2
示例 3:
輸入: [7,8,9,11,12]
輸出: 1
說明:
你的算法的時間複雜度應爲O(n),並且只能使用常數級別的空間。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/first-missing-positive
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
題解:
- 假設N個數組合爲1、2 、3.....、n,則未出現的數爲可能的最大值n+1
- 任意組合未出現的數不會超過n+1
- 用 長度爲n+1的boolean數組來標記當前下標 i 是否在數組中出現
- 從下標1開始遍歷boolean數組 找出未出現的第一個數字即可
class Solution {
public int firstMissingPositive(int[] nums) {
//因爲N個數最多隻能映射1-N,此時缺失的第一個正數爲N+1
//所以返回值不超過N+1
boolean[] ret = new boolean[nums.length+2];//前部加0(最後會棄用)、尾部添加一個哨兵,爲最大返回值
for(int i=0 ; i<nums.length ; i++){
if(nums[i]<=0 || nums[i]>nums.length){//過濾掉負數和超過長度的數
continue;
}
ret[nums[i]] = true;//當前數字標記存在
}
for(int i=1 ; i<ret.length ; i++){
if(!ret[i]){
return i;//未出現的i
}
}
return 1;//nums爲空時返回1
}
}