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.
solution:
store nums[i] at index nums[i]-1
public int firstMissingPositive(int[] nums) {
for(int i=0;i<nums.length;i++){
while(nums[i]<= nums.length && nums[i]>0 && nums[nums[i] -1]!= nums[i]) {
int temp = nums[i];
nums[i] = nums[nums[i] - 1];
nums[temp - 1] = temp;
}
}
for(int i=0;i<nums.length;i++){
if(nums[i]!= i+1) return i+1;
}
return nums.length +1;
}

本文介绍了一种在未排序整数数组中查找第一个缺失正整数的算法,该算法能在O(n)时间内运行并使用常量空间。通过将数值存放在对应下标的正确位置上实现高效查找。
782

被折叠的 条评论
为什么被折叠?



