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) ☆