【60】41. First Missing Positive

41. First Missing Positive

Description Submission Solutions Add to List

  • Total Accepted: 87522
  • Total Submissions: 350444
  • Difficulty: Hard
  • Contributors: Admin

 

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.

class Solution {
public:
//把数组遍历一遍,存入hashmap。再从1开始往后找,找不到则返回i,否则返回最大值加一。
    int firstMissingPositive(vector<int>& nums) {
        unordered_map<int, int> hash;
        int mx = 0;
        for(int num : nums){
            hash[num]++;
            if(num > mx){
                mx = num;
            }
        }
        for(int i = 1; i <= mx; i++){//这里是<= max
            if(hash.find(i) == hash.end()){
                return i;
            }
        }
        return mx + 1;
    }
};

 

posted @ 2017-02-12 14:01  会咬人的兔子  阅读(131)  评论(0编辑  收藏  举报