您的位置:首页 > 其它

LeetCode(7) - First Missing Positive

2017-04-18 20:07 369 查看
https://leetcode.com/problems/first-missing-positive/#/description

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:

本题的的目的是在于寻找第一个缺失的整数,方法有两种。

一种是新开一个数组,由于要使用常数空间,所以这种不行。

一种是对数组进行简单排序,我们的思路是将非负数放到其对应的Index上,例如1就放到0,2就放到1,以此类推。

最后遍历数组,寻找index不符合的数值输出。

这里有两点需要注意的:

1、交换位置时,需要持续交换,直到满足出现非负数或者符合当前index的数

2、注意[1, 1]这样的情况,容易导致1卡死。

public int firstMissingPositive(int[] nums) {
for(int i = 0; i < nums.length; i++) {
while(nums[i] > 0 && nums[i] <= nums.length && nums[i] != i + 1) {
if (nums[i] == nums[nums[i] - 1]) {
break;
}
int temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
}

for(int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}

return nums.length + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: