码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 41. First Missing Positive

时间:2019-01-05 21:30:55      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:constant   example   ali   style   The   题意   first   miss   ted   

41. First Missing Positive

题目链接:https://leetcode.com/problems/first-missing-positive/

Description:

Given an unsorted integer array, find the smallest missing positive integer.Your algorithm should run in O(n) time and uses constant extra space.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

题意:

给出n个无序的数,问缺失的最小正数是多少,要求在O(N)时间内解决问题。

 

题解:

注意到答案只能在1~n+1之间,那么我们就可以统计给出的数中在1~n中是否出现,判断下就好了。

 

代码如下:

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();
        int vis[n+2]={0};
        for(int i=0;i<n;i++){
            if(nums[i]>=1 && nums[i]<=n) vis[nums[i]]=1;
        }
        for(int i=1;i<=n;i++) if(!vis[i]){
            return i;
        }
        return n+1 ;
    }
};

 

Leetcode 41. First Missing Positive

标签:constant   example   ali   style   The   题意   first   miss   ted   

原文地址:https://www.cnblogs.com/heyuhhh/p/10226089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!