First Missing Positive
Problem:
Given an unsorted integer array, find the first missing positive integer.
Ideas:
A[a[i] [= A[i] Classic applications
My Code:
Public classSolution { Public intFirstmissingpositive (int[] nums) { if(nums==NULL|| nums.length==0)return1; intLen =nums.length; inti = 0; while(I <Len) { if(Nums[i] <= 0) {i++; } Else { intindex =Nums[i]; if(Index >Len) {Nums[i]= 0; I++; } Else { if(Nums[index-1] = = index) i++; Else { intTMP = Nums[index-1]; Nums[index-1] =Nums[i]; Nums[i]=tmp; } } } } for(intk=0; k<len; k++) { if(Nums[k]! = k+1)returnK+1; } returnLen+1; } }
View Code
Others code:
//Solution 2: Public intFirstmissingpositive (int[] A) {//bug 3:when length is 0, return 1; if(A = =NULL) { return0; } for(inti = 0; i < a.length; i++) { //1:a[i] is in the range; //2:a[i] > 0. //3:the target is different; while(A[i] <= a.length && a[i] > 0 && a[a[i]-1]! =A[i]) {Swap (A, I, A[i]-1); } } for(inti = 0; i < a.length; i++) { if(A[i]! = i + 1) { returni + 1; } } returnA.length + 1; }
View Code
The Learning Place:
- Carefully below this piece of code, each a[i] has a mission, what is called the end of the mission, after the ups and downs of the process A[i] The value of several changes, but a[a[i] [= A[i] succeeded, at this moment the mission is over.
while (A[i] <= a.length && a[i] > 0 && a[a[i]-1]! = A[i]) {-1); }
View Code
First Missing Positive