First Missing Positive
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.
Idea: This problem is not at the beginning of the idea, difficult on the O (n) time in a constant amount of space, so this topic more investigation of thinking agility. The core idea of solving the problem is to put the i+1 of the array in the positive position. The last one can be traversed again.
Other people's thoughts, I also read the idea of the code of their own writing.
Although it is not possible to create additional extra space in a number of different levels, swap operations can be done in place on the input array.
idea : Swap array elements so that the first bit of the array holds the value (i+1). Finally, the array is traversed, looking for the first element that does not meet this requirement, and returns its subscript. The entire process needs to traverse an array of two times, with an O (n)degree of complexity.
Take the second example given in the topic to explain the operation process.
Mom, this is a long struggle. First of all, the next critical condition, the problem is similar to the following:
N An array of elements, the number of which is 0~n-1 One of the elements in the array that is repeated in the range, no return -1, Time Performance Required O (n) Space Performance O (1).
The code is still relatively simple, as follows:
public class Solution {public int firstmissingpositive (int[] nums) { if (nums.length = = 0) return 1; The value of the i+1 stored for (int i = 0; i < nums.length;i++) { if (Nums[i] > 0) {//nums[i] is positive, placed in i+1 position // If the data exchanged is still greater than 0 and <i+1, then put in the appropriate position, and the data is not equal, to avoid the dead loop //This while is the key, others are not difficult while (Nums[i] > 0 && nums[i] < i+1 && Nums[i]! = Nums[nums[i]-1]) { int temp = nums[nums[i]-1];//interchange data nums[nums[i]-1] = nums[i];
nums[i] = temp;}} } Loop to find data that does not meet the requirements, return for (int i = 0; i < nums.length;i++) { if (nums[i]! = i+1) { return i+1;} } ///If all meet the requirements, return the value of length +1 to Nums.length + 1;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 41.First Missing Positive (first missing positive number) thinking and method of solving the problem