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
.
Ideas:
The exchange is constant and the number of values I is exchanged to the position of (i-1) th.
PackageArray; Public classfirstmissingpositive { Public intFirstmissingpositive (int[] nums) { intN; if(Nums = =NULL|| (n = nums.length) = = 0)return1; for(inti = 0; I < n; ++i) {intA =Nums[i]; while(A > 0 && a <= n && nums[i]! = i + 1 && nums[a-1]! =a) {swap (nums, I, a-1); A=Nums[i]; } } intj = 0; while(J < n && nums[j] = = j + 1){ ++J; } returnJ + 1; } Private voidSwapint[] Nums,intIintj) {intTMP =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=tmp; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] Nums = { }; Firstmissingpositive F=Newfirstmissingpositive (); System.out.println (F.firstmissingpositive (nums)); }}
Leetcode-first Missing Positive