// 5.7
// 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.
public int firstMissingPositive(int[] nums) {
int idx = 0;
while (idx < nums.length) {
if (nums[idx] == idx + 1 || nums[idx] <= 0 || nums[idx] > nums.length) {
idx++;
} else {
if (nums[idx] == nums[nums[idx] - 1]) {
idx++;
} else {
swip(nums, idx, nums[idx] - 1);
}
}
}
idx = 0;
while (idx < nums.length && nums[idx] == idx + 1) {
idx++;
}
return idx + 1;
}
void swip(int[] ary,int x,int y) {
int temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
给一整数无序数组,找到第一个缺失的正整数,时间复杂度为n
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。