首页 > 其他 > 详细

【60】41. First Missing Positive

时间:2017-02-12 14:46:07      阅读:231      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

【60】41. First Missing Positive

原文:http://www.cnblogs.com/93scarlett/p/6390872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!