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