题目:
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.
分析(原创):class Solution {
public int firstMissingPositive(int[] nums) {
//类似在给定长度数组中查找唯一重复的一个,使用交换策略,将元素与其应该归属的位置进行对比
//该题需要超找第一个丢失的正数
//要求:时间复杂度为n,所以不能排序,只能使用常数个变量
//[]=>1 [1]=>2
if(nums.length==0||nums==null) return 1;
boolean [] flag=new boolean[nums.length+1];
for(int i=0;i<nums.length;i++){
if(nums[i]>0&&nums[i]<=flag.length){
flag[nums[i]-1]=true;
}
}
for(int i=0;i<flag.length;i++){
if(!flag[i]){
return i+1;
}
}
return 1;
}
}