"One Day together Leetcode" #41. First Missing Positive

Source: Internet
Author: User

One Day Together Leetcode series (i) Title

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.

(ii) Problem solving
/ * First sort the initial vector, then set a target=1 starting from the first number greater than 0, if it equals the number of target, + 1, until the next number cannot be reached at target. If the array is not returned if it is found, The target+1 is returned; Of course there is a special case to consider: there are duplicates in the array that need to be excluded */classSolution { Public:intFirstmissingpositive ( vector<int>& Nums) {sort (Nums.begin (), Nums.end ());inttarget =1; for(inti =0; I < nums.size (); i++) {if(nums[i]>0)            {if(Nums[i] = = target) {target++;//Note that this is already + 1, and finally returns to the target directly}Else if(i>0&&nums[i]!=nums[i-1])//Exclude duplicate numbers{returnTarget }            }        }returnTarget//If no vacancy is found, return to Target+1}};

"One Day together Leetcode" #41. First Missing Positive

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.