Topic
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.
"Analyze"
1. Because it is disorderly, it is a bit cumbersome to deal with. Consider placing the correct positive number at the correct index position, and then traversing the entire array
2. There are two places that have not been noticed: first, after the current position exchange, also need to judge; Ii. if you solve the first problem (join while), the current value and the value of the interchange will enter the dead loop
Algorithm
v1: A rather shameless approach, sorted first Public classSolution { Public intFirstmissingpositive (int[] nums) {Arrays.sort (nums); intFlag=1; intI=0; while(i<nums.length) {if(nums[i]>0) { if(nums[i]==flag) {Flag++; I++; while(i<nums.length&&nums[i]==nums[i-1]) I++; }Else returnFlag; }ElseI++; } returnFlag; }}V2: Public classSolution { Public intFirstmissingpositive (int[] nums) { if(nums==NULL|| Nums.length<1) return1; intlen=nums.length; for(inti=0;i<nums.length;i++) { while(nums[i]!=i+1&&nums[i]>0&&nums[i]<=Len) { if(nums[i]==nums[nums[i]-1]) Break; inttemp=Nums[i]; Nums[i]=nums[temp-1]; Nums[temp-1]=temp; } } for(inti=0;i<len;i++) { if(nums[i]!=i+1) returnI+1; } returnLen+1; }}
41-first Missing Positive