题目
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
示例 1:
输入:nums = [1,2,0]
输出:3
示例 2:
输入:nums = [3,4,-1,1]
输出:2
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
方法一
从1开始遍历
const firstMissingMinNumber = function (nums) {
let res = 1;
while (true) {
if (nums.includes(res)) {
res++;
} else {
return res;
}
}
};
时间复杂度:O(n2)
空间复杂度:O(1)
方法二
使用
set数据结构
const firstMissingMinNumber = function (nums) {
const set = new Set(nums);
for (let i = 1; i <= nums.length + 1; i++) {
if (!set.has(i)) {
return i;
}
}
};
时间复杂度:O(n)
空间复杂度:O(n)