题目名称
First Missing Positive
描述
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Subscribe to see which companies asked this question
分析
给定的数组中可能包含重复的整数,可能会有非常大的整数,要在这些整数中寻找出丢失的最小正整数,所以数组中每个元素都要遍历一遍,对原数组进行排序时间复杂度至少为O(nlogn)。
STL中map可以解决这个问题,map中的key是按照升序自动排序的,这样,我们只需要遍历一次原数组,将出现的正整数存入到一个map中,key为正整数,value为该正整数出现的次数,最后遍历一次map即可找到丢失的最小正整数了,时间复杂度为O(n)。
C++代码
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int length = nums.size();
map<int,int> temp;
for(int i=0;i<length;++i){
if(nums[i]>0)
temp[nums[i]]++;
}
int i=1;
for(auto iter=temp.begin();iter!=temp.end();++iter){
if(iter->first == i)
i++;
else
return i;
}
return i;
}
};
总结
STL map和unordered_map的运用,总结一下他们的异同。