题目
法1:哈希表
实际上,对于一个长度为N的数组,其中没有出现的最小正整数只能在 [1, N + 1]中。这是因为如果[1, N] 都出现了,那么答案是 N + 1,否则答案是[1, N] 中没有出现的最小正整数。
class Solution {public int firstMissingPositive(int[] nums) {boolean[] array = new boolean[nums.length];Arrays.fill(array, false);for (int n : nums) {if (n > 0 && n <= nums.length) {array[n - 1] = true;}}for (int i = 0; i < array.length; ++i) {if (!array[i]) {return i + 1;}}return nums.length + 1;}
}
法2
其他方法参见:https://leetcode.cn/problems/first-missing-positive/solutions/304743/que-shi-de-di-yi-ge-zheng-shu-by-leetcode-solution/?envType=study-plan-v2&envId=top-100-liked