[Leetcode] First Missing Positive
2017-03-13 03:46
369 查看
弄一篇博客总是比较痛苦的,因为要炒冷饭。
半夜被舍友的机械键盘吵得痛不欲生,于是干脆不睡了,整理下最近做的几道水题。
题目链接在此
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
and
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)。
半夜被舍友的机械键盘吵得痛不欲生,于是干脆不睡了,整理下最近做的几道水题。
题目链接在此
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 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 First Missing Positive
- LeetCode 41 First Missing Positive
- [Leetcode] First Missing Positive
- LeetCode: first Missing Positive
- leetcode First Missing Positive
- LeetCode41 - 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》first-missing-positive