"Leetcode" first Missing Positive (hard) ☆

Source: Internet
Author: User

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.

Ideas:

It's another one, but it's about sorting information. Think for a while, only space for time, but also can only use constant space, this can be difficult to me. I can't think of it at all. Give up looking at the answer.

Found that the answer is actually a space for the idea of time, but the space here directly used the first array.

The concrete idea is: Start with the first number, and change the positive numbers to the sorted positions. That is 1 put to position 0,2 put to position 1. The number until the current position becomes the correct number. If a number less than 0 or more than the number of elements skipped, because if there is a corresponding position of the number will be replaced.

Code:

classSolution { Public:    intFirstmissingpositive (vector<int>&nums) {         for(inti =0; I < nums.size (); ++i) { while(Nums[i] >0&& Nums[i] <= nums.size () && Nums[nums[i]-1] !=Nums[i]//Actually here do not nums[i] > 0 can also be a bit slower swap (nums[i], nums[nums[i]-1]); Swap digits until the current position is correct or the number cannot be placed sequentially in the current matrix}inti;  for(i =0; I < nums.size (); ++i) {if(Nums[i]! = i +1)                 Break; }        returni +1; }};

"Leetcode" first Missing Positive (hard) ☆

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.