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卡死。
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; }
相关文章推荐
- [LeetCode 41] First Missing Positive
- LeetCode First Missing Positive
- LeetCode-First Missing Positive
- Leetcode First Missing Positive
- LeetCode First Missing Positive
- 【leetcode】Array——First Missing Positive(41)
- [Leetcode] First Missing Positive
- LeetCode 41 First Missing Positive
- LeetCode: first Missing Positive
- LeetCode41 - First Missing Positive
- leetcode-First Missing Positive
- [LeetCode]题解(python):041-First Missing Positive
- LeetCode_41---First Missing Positive
- LeetCode | First Missing Positive(第一个缺失的正整数)
- [LeetCode] First Missing Positive
- Leetcode First Missing Positive
- LeetCode | First Missing Positive
- LeetCode 112 First Missing Positive
- LeetCode First Missing Positive
- 《leetcode》first-missing-positive