Leetcode Note: First Missing Positive

Source: Internet
Author: User

Leetcode Note: First Missing Positive

I. Description

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

For example,
Given[1,2,0]Return3,
And[3,4,-1,1]Return2.

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

Ii. Question Analysis

The general idea of this question is to give an unordered array, which may contain zero or positive negative numbers. It is required to find the first unordered positive number. For example[1, 2, 0]Because the first undisplayed positive integer is3, Returns3;[3, 4, -1, 1]The first undisplayed positive integer is2, Returns2. The algorithm requirements are as follows:O(n)Time Complexity and constant space complexity.

One way is to first extract each positive integer from the arrayiPlacei-1In this way, an ordered sequence is formed, and then each cursor is checked.indexWith the current element value, you can know whether the positive integer corresponding to the current subscript is missing. If it is missing, the subscript is returned.index + 1You can.

Iii. Sample Code

#include 
  
   #include 
   
    using namespace std;class Solution{public:    int firstMissingPositive(vector
    
     & nums)    {        int n = nums.size();        for (int i = 0; i < n; ++i)        {            int temp = 0;            while (i + 1 != nums[i] && nums[i] != nums[nums[i] - 1] && nums[i] > 0)            {                temp = nums[i];                nums[i] = nums[temp - 1];                nums[temp - 1] = temp;            }        }        for (int i = 0; i < n; ++i)        {            if (i + 1 != nums[i])                return i + 1;        }        return n + 1;    }};
    
   
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.