Leetcode Note: First Missing Positive
I. Description
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 shocould run in O (n) time and uses constant space.
Ii. Question Analysis
The general idea of this question is to give an unordered array, which may contain zero or positive negative numbers. It is required to find the first unordered positive number. For example[1, 2, 0]Because the first undisplayed positive integer is3, Returns3;[3, 4, -1, 1]The first undisplayed positive integer is2, Returns2. The algorithm requirements are as follows:O(n)Time Complexity and constant space complexity.
One way is to first extract each positive integer from the arrayiPlacei-1In this way, an ordered sequence is formed, and then each cursor is checked.indexWith the current element value, you can know whether the positive integer corresponding to the current subscript is missing. If it is missing, the subscript is returned.index + 1You can.
Iii. Sample Code
#include
#include
using namespace std;class Solution{public: int firstMissingPositive(vector
& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { int temp = 0; while (i + 1 != nums[i] && nums[i] != nums[nums[i] - 1] && nums[i] > 0) { temp = nums[i]; nums[i] = nums[temp - 1]; nums[temp - 1] = temp; } } for (int i = 0; i < n; ++i) { if (i + 1 != nums[i]) return i + 1; } return n + 1; }};