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.
Test instructions
Given an unordered array, it is required to find the first missing positive integer. The first missing positive integer, such as 1,2,4,5, is 3. Requires a time complexity of O (n) space complexity O (1)
Ideas:
The first kind is sort, the time complexity is O (NLGN) No
The second is the hash lookup for each number using extra space to find the correct location. Then a traversal finds the first missing positive integer. The time complexity is O (n) But the space complexity is O (n) also does not meet the requirements of the topic
The third is to exchange operations directly on the input array, so that each number can be exchanged in the correct position. such as 3,1,7,2 this set of numbers after the first exchange to get 7,1,3,2 number 3 is placed in the correct position.
This time complexity is O (n) and only constant auxiliary space is required. But I think this method still does not compound the title requirement, because it destroys the original array. It is also similar to a hash, which requires O (n) space, except that the space of O (n) is borrowed from the original input array.
So far, I haven't found a way to destroy the original array, the spatial complexity and the O (1).
Code 1 (hash method):
classSolution { Public: intFirstmissingpositive (vector<int>&nums) { if(nums.size () = =0) return 1; Auto It_max=std::max_element (Nums.begin (), Nums.end ()); Auto It_min=std::min_element (Nums.begin (), Nums.end ()); Vector<BOOL> Vec (*it_max-*it_min,false); for(auto elem:nums) Vec[elem-*it_min] =true; for(Auto it =1; It <= *it_max; ++it) { if(It < *it_min | | (It >0&&!vec[it-*It_min])) returnit; } return*it_max >0? *it_max +1:1; }Private:};
Code 2 (Exchange directly on the original array, the space cost is O (1))
classSolution { Public: intFirstmissingpositive (vector<int>&nums) { if(Nums.empty ())return 1; Auto Begin=Getfirstpositivepos (nums); if(*begin <0) return 1; for(Auto it = begin; It! =nums.end ();) {Auto RealPos= begin + *it-1; if(RealPos < Nums.end () && realPos! = It && *realpos! = *it) Iter_swap (it, realPos); Else++it; } intindex =1; for(Auto it = begin; It! = Nums.end (); ++it, index++) { if(Index! = *it)returnindex; } returnindex; }Private: Vector<int>::iterator Getfirstpositivepos (vector<int>&nums) {Auto First=Nums.begin (); Auto Last= Nums.end ()-1; while(true) { while(First < last && *first <=0 ) ++First ; while(First < last && *last >0) --Last ; if(First <Last ) Iter_swap (first, last); Else Break; } returnFirst ; }};
Leetcode problem--First Missing Positive