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.
Problem solving idea One:
Just see the topic when feel not start, and then carefully understand test instructions, need to find first missing positive integer, only need to find the only one, so we can open a Boolean array, storage I exist, Java implementation is as follows:
public int firstmissingpositive (int[] nums) {boolean[] num=new boolean[nums.length + 1]; for (int i = 0; i < nums.length; i++) if (Nums[i] > 0&&nums[i] <= nums.length) num[nums[i]-1] = t Rue; for (int i = 0; i < num.length; i++) if (!num[i]) return i+1; return 0; }
Two: The use of bool array will have O (N) space complexity, the direct use of the Exchange method can be avoided, Java implementation is as follows:
static public int firstmissingpositive (int[] nums) { if (nums.length==0) return 1; for (int i = 0; i < nums.length;) { if (Nums[i] >= 0 &&nums[i] < nums.length &&nums[i]! = i && nums[i]! = Nums[nums[i]]) { C5/>int Temp=nums[i]; Nums[i]=nums[nums[i]]; nums[temp]=temp; } else i++; } for (int i = 1; i < nums.length; ++i) if (nums[i]! = i) return i; return Nums[0] = = Nums.length? Nums.length + 1:nums.length; }
Java for Leetcode 041 first Missing Positive