首页 > 其他 > 详细

LeetCode开心刷题二十二天——41. First Missing Positive

时间:2019-07-20 11:44:23      阅读:81      评论:0      收藏:0      [点我收藏+]
41. First Missing Positive
Hard

Given an unsorted integer array, find the smallest missing positive integer.

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

Note:

Your algorithm should run in O(n) time and uses constant extra space.

ATTENTION:

we need to find the relationship between subscripts and array value.

Correct order is the subscripts i corresponding i+1,which means arr[i]=i+1;

So if you find this value is not the correct corresponding just swap it to the right place.

 

if(arr[i]!=i+1&&arr[i]>=1&&arr[i]<=n&&arr[arr[i]-1]!=arr[i])
This code is the most important one,but you need to pay attention that if arr[i]-1<0
the arr will outrange so when we dealing with arrays we need to pay attention to its
subscripts

 

#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<vector>
#include<list>
#include<queue>
#include<algorithm>
#include<stack>
#include<map>
using namespace std;
//solve function
class Solution
{
public:
    int firstMissingPositive(vector<int>& arr)
    {
        int res,n=arr.size();
        for(int i=0;i<n;)
        {
            if(arr[i]!=i+1&&arr[i]>=1&&arr[i]<=n&&arr[arr[i]-1]!=arr[i])
            {
                swap(arr[i],arr[arr[i]-1]);
            }
            else
            {
                i++;
            }
        }
        for(int i=0;i<n;i++)
        {
            if(arr[i]!=i+1)
            {
                res=i+1;
                return res;
            }

        }
        res=n+1;
        return res;
    }
};
int main()
{
    Solution s;
    vector<int> arr={0,0,2};
    int res;
    res=s.firstMissingPositive(arr);
    cout<<res<<endl;
    return 0;
}

 

 

LeetCode开心刷题二十二天——41. First Missing Positive

原文:https://www.cnblogs.com/Marigolci/p/11216840.html

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