[LeetCode] [Java] First Missing Positive
Question:
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.
Question:
Given an unordered integer array, find the first missed positive integer.
For example:
Given[1,2,0]3,
[,-] Returns 2.
The algorithm requires O (n) time complexity and constant space.
Algorithm analysis:
The simplest way is to sort arrays quickly. However, due to the time complexity of O (n), fast sorting is obviously not feasible.
Therefore, in order to search for elements, the subscript of the array is used as its index, that is, the elements of the array are exchanged and positive numbers are
iPut in
i-1The negative number and elements greater than the array length are discarded. In this way, the first nonexistent positive number can be obtained by scanning the array linearly, that is, the first
jThe position element is not equal
j+1.
AC code:
Public class Solution {public int firstMissingPositive (int [] A) {// place A positive number to the position of-1, so that 1 is placed at position 0, 2 is placed in the position on the 1st ,.... If (A = null | A. length = 0) return 1; for (int I = 0; i0 & A [A [I]-1]! = A [I]) // here A [A [I]-1]! = A [I] indicates that {int temp = A [A [I]-1] is not exchanged if the condition has been met. A [A [I]-1] = A [I]; A [I] = temp; I -- ;}} for (int I = 0; I