您的位置:首页 > 其它

[Leetcode] First Missing Positive

2017-03-13 03:46 369 查看
弄一篇博客总是比较痛苦的,因为要炒冷饭。

半夜被舍友的机械键盘吵得痛不欲生,于是干脆不睡了,整理下最近做的几道水题。

题目链接在此

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.

用O(n)的时间和O(1)的空间,寻找数组中缺失的最小的正整数。
有点像 448.Find All Numbers Disappeared in an Array  这道题。

大体思想就是把每个数放到它对应下标那里。比如说,把3放到a[2],把5放到a[4]等等。
代码如下。因为每个数最多被交换一遍,所以虽然有2层循环,但是时间复杂度还是O(n)。

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int tmp = nums[i];
nums[i] = nums[tmp - 1];
nums[tmp - 1] = tmp;
}
}

for (int i = 0; i < n; i++) {
if (nums[i] != i + 1)
return i + 1;
}
return n + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode