题目
Given an unsorted integer array, find the smallest missing positive integer.
找出数组中缺少的最小正整数(0不是正数)
- Example1
Input: [1,2,0]
Output: 3
- Example2
Input: [3,4,-1,1]
Output: 2
- Example3
Input: [7,8,9,11,12]
Output: 1
- 解法
var firstMissingPositive = function(nums) {
let smallest = 1;
let store = {}
for(let i = 0; len = nums.length, i < len; i++){
// 将数组的值作为对象的key,每个key的值为1
store[nums[i]] = 1;
}
for(let key in store){
// 因为找缺少的最小整数,所以我们从1开始数,1,2,3...
// 如果缺少3,那么store对象的key就没有3,所以store[3]>1为false,此时的smallest为3就是我们需要的
if(store[smallest] > 1){
smallest++
}
}
return smallest
};
网友评论