[LeetCode] First Missing Positive
来源:互联网 发布:淘宝前十名服装店铺 编辑:程序博客网 时间:2024/06/06 09:05
题目
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) 时间运行,并使用恒定空间。
分析
假设数组为 a ,找正整数, 最好的情况是 a[i] == i + 1
,如果不满足此条件,数组内又无对应的正整数,就找到了第一个缺失的正整数。
如此一来,主要思路就是在遍历数组是判断每个位置是否有对应的正整数,主要分为以下三种情况。
- 满足最好情况——
a[i] == i + 1
,继续判断数组下一个元素。 - 该数不在考虑范围内——如该数为非正数数或大于数组长度,或者该数应放的正确位置已经有的正确的数,此时可以直接扔掉该数,也就是将数组长度减一,把末尾数移到该位置,重新判断数组。
- 以上两个条件都不满足,可以将该数它应在的位置上,重新判断数组。
代码
#include <iostream>#include <vector>using namespace std;class Solution {public: int firstMissingPositive(vector<int>& nums) { int length = nums.size(); for (int i = 0; i < length;) { if (nums[i] == i + 1) { i++; } else if ((nums[i] <= i) || (nums[i] > length) || (nums[nums[i] - 1] == nums[i])) { nums[i] = nums[--length]; } else { swap(nums[i], nums[nums[i] - 1]); } } return length + 1; }};int main() { int num[] = {3, 4, -1, 1}; int length = sizeof(num) / sizeof(int); vector<int> nums(num, num + length); Solution solution; int number = solution.firstMissingPositive(nums); cout << "The first missing positive integer is " << number << endl;}
阅读全文
0 0
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- LeetCode First Missing Positive
- [leetcode] first missing positive
- LeetCode: First Missing Positive
- [LeetCode]First Missing Positive
- LeetCode-First Missing Positive
- [leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- LeetCode - First Missing Positive
- LeetCode | First Missing Positive
- Leetcode: First Missing Positive
- Leetcode:First Missing Positive
- Activity的显示启动和隐式启动
- 恶意代码分析实战课后题 Lab11-03
- 汽车拉力比赛
- runloop 基础学习
- Axure中继器结构与原理详解
- [LeetCode] First Missing Positive
- HTML5表单教程之input新增加的几种时间类型
- 笨办法学 Python · 续 练习 1:流程
- redis关闭方法
- “军装照”背后——天天P图如何应对10亿流量的后台承载
- decode()函数使用
- oracle11.2.0.1.0 连接 python3.5.1
- Qt之图形视图框架
- vb.net 用户自定义类型详解