First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
Return3
,
and[3,4,-1,1]
Return2
.
Your algorithm should run in O(n) time and uses constant space.
Problem Solving Ideas:
This problem is very good, the most direct thought is (1) sort, then scan, or (2) use an array to record the values that have occurred. But the problem requires time complexity of O (n), spatial complexity is constant, (1) Method time complexity is O (Nlogn), (2) method space complexity is O (n), all do not meet the requirements.
A very impressive approach is the idea of swapping, moving a number of values to a nums[a-1] (if a is within the allowable range). Finally, the array is scanned again, found that the value is not equal to its subscript +1 is the request.
There are two points to note:
(1) There may be multiple identical values. If two values are the same, no Exchange
(2) Note that the subscript starts at 0 and the value starts at 1.
Class Solution {public: int firstmissingpositive (vector<int>& nums) { int len = Nums.size (); for (int i=0; i<len;) { if (nums[i]>0 && nums[i]<=len && nums[i]!=i+1 && nums[i]!=nums[nums[i]-1]) { Swap (Nums, I, nums[i]-1); } else{ i++; } } for (int i=0; i<len; i++) { if (i + 1! = Nums[i]) { return i + 1; } } return len + 1; } Private: void Swap (vector<int>& nums, int i, int j) { int temp = nums[i]; Nums[i] = nums[j]; NUMS[J] = temp; }};
[Leetcode] First Missing Positive