您的位置:首页 > 其它

41. First Missing Positive

2017-03-13 16:26 211 查看

题目First Missing Positive

题目介绍

原题链接: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.

给出一个未排序的序列,找出序列中没有出现的最小的正整数。

例:

序列: [1,2,0],那么返回 3

序列:[3,4,-1,1], 那么返回 2.

算法要求时间复杂度O(n),并且使用常熟级别的空间复杂度。

思路

核心思想还是想办法把每个出现过的正整数都标记出来。

假设数组长度为len,那么未出现的最小整数肯定在1到len + 1之间。

首先遍历数组,把小于1或者大于len的元素都替换成len + 1.

再次遍历数组,对于每一个元素 a,如果它表示的绝对值在1到len之间,那么把nums[ a - 1]表示负数,变成负数是用来表示当前下标(即正整数)已经出现过,之所以是a - 1,是为了把1到 len的正整数映射到数组下标0到len - 1上。

最后遍历一次数组,如果某一个下标对应的元素不是负的,说明对应的正整数(记得加1)没有出现过,输出它,如果遍历结束了,那么说明1到len都出现了,输出len + 1.

代码

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int len = nums.size();
if(!len) return 1;
if(len == 1) return nums[0] == 1 ? 2 : 1;
for(int i = 0; i < len; ++i) {
if(nums[i] < 1 || nums[i] > len) nums[i] = len + 1;
}
for(int i = 0; i < len; ++i) {
int temp = nums[i];
if(temp < 0) temp = -temp;
if(temp == len + 1) continue;
if(nums[temp - 1] > 0) nums[temp - 1] = -nums[temp - 1];
}
for(int i = 0; i < len; ++i) {
if(nums[i] > 0) return i + 1;
}
return len + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode