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 shold run inO(N) Time and uses constant space.
Algorithm analysis:
Set ~ The number of A. length is placed at the corresponding position of the subscript. Other plural values or values greater than a. length are not processed.
Then traverse a again and find the first default integer.
[Note] processing of repeated numbers and negative numbers; I should be placed in the I-1 position, but if I-1 is also placed in the I-1 position, skip; if it is not a positive number, skip; skip if the number is too large;
The Code is as follows:
1 public class Solution { 2 public int firstMissingPositive(int[] a) { 3 if(a == null || a.length == 0) return 1; 4 int length = a.length; 5 for(int i = 0; i < length; i++){ 6 if(a[i] > length - 1 || a[i] <= 0 || a[i] == a[a[i] - 1]) continue; 7 int t = a[a[i] - 1]; 8 a[a[i] - 1] = a[i]; 9 a[i] = t;10 i--;11 }12 int positive = 1;13 for(int i = 0; i < length; i++){14 if(a[i] <= 0) continue;15 if(a[i] == positive){16 positive++;17 }else{18 return positive;19 }20 }21 return positive;22 }23 }
This question is very good.