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.
题目:在一个无序的数组中找出第一题个缺少的正整数。
思路:因为空间复杂度要求是O(n)以及不能新增新的数组。所以思路是先排序,然后从小开始遍历,遇到第一个就输出就行了,但是要注意这个数组是可以重复的,一开始没注意这个限制条件。
public int firstMissingPositive(int[] nums) {
if(nums.length == 0) {
return 1;
}
Arrays.sort(nums);
int j = 1;
for(int i = 0;i < nums.length;i++) {
if(nums[i] > 0) {
if(nums[i] != j) {
return j;
} else if(i < nums.length-1 && nums[i] != nums[i+1]) {//排除重复的数字
j++;
}
}
}
return nums[nums.length-1]+1;
}