给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0] 输出: 3
示例 2:
输入: [3,4,-1,1] 输出: 2
示例 3:
输入: [7,8,9,11,12] 输出: 1
说明:
你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
分析:
就是对整个数组的元素进行计数就行了
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
// 使用map对每一个数进行计数
map<int,int> count;
for(int num:nums){
if(num <= 0)continue;
count[num]++;
}
// 遍历map
map<int,int>::iterator curr = count.begin();
for(int i=1; i<INT_MAX; i++){
if(count.count(i)) continue;
return i;
}
return 0;
}
};