First Missing Positive--LeetCode
来源:互联网 发布:网络配置代码 编辑:程序博客网 时间:2024/06/05 03:34
1.题目
First Missing Positive
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.
2.题意
给定一个未排序的整数数组,找到第一个缺少的正整数
要求用线性时间和常量空间
3.分析
借助计数排序的思想
利用数组下标作为索引,把正数按照递增顺序依次放到数组中
即让A[0]=1, A[1]=2, A[2]=3, …
如果结果数组违反了A[i]=i+1
那么i+1就是第一个缺失的整数
对于不在范围内的数字,直接跳过,如负数,0,或者超过数组长度的正整数
4.代码
class Solution {public: int firstMissingPositive(vector<int>& nums) { int len = nums.size(); int i = 0; while(i < len) { if(nums[i] >= 1 && nums[i] <= len && nums[i] != i + 1 && nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]); else ++i; } for(i = 0; i < len; ++i) { if(nums[i] != i + 1) return i + 1; } return len + 1; }};
阅读全文
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
- ORM
- #########WOE 评分模型 在logistics regression算法在评分卡上的实践
- MySQL数据库安装与配置详解
- Ubuntu下给普通或新增用户赋予sudo权限
- zabbix监控一---zabbix服务端部署
- First Missing Positive--LeetCode
- python 包发布
- 混淆矩阵(Confusion Matrix)分析
- 2017.10.30 覆盖问题 思考记录
- 李开复给中国大学生的七封公开信(其七)
- SSL2454 NOIP2015提高组模拟题八 采药(背包dp)
- 匹配 (KMP)
- Lua 字符串的使用
- Previous operation has not finished; run 'cleanup' if it was interrupted