Leetcode First Missing Positive
来源:互联网 发布:北京和隆优化 编辑:程序博客网 时间:2024/06/06 01:41
Leetcod First Missing Positive,本算法使用hash表实现,此外注意到positive从1开始,而给出的数组至有多len(arr)个positive,而且有如下几种情况:
- 元素为负数,那么一定不会对计算positive产生影响
- 元素为正数,但是元素大于len(arr),此时也不会对结果有影响,因为此时在1到len(arr)这些数中一定会有空出的元素,因此大于len(arr)的元素可以直接忽略
- 元素在1到len(arr)之间,此时我们使用一张flag的数组记录对就的正整数i是否出现,若出现则记为true
最后,可以扫描flag数组,如果数组中有空缺,则第一个缺为最小正整数,如果没有空缺,最小正整数为len(arr) + 1。
相关代码如下,算法时间复杂度为o(n):
#include<iostream>#include<vector>using namespace std;class Solution {public: int firstMissingPositive(vector<int>& nums) { vector<bool> flag(nums.size() + 1, false); for (int i = 0; i < nums.size(); i ++) { if (nums[i] >= 0 && nums[i] <= nums.size()) { flag[nums[i]] = true; } } for (int i = 1; i < flag.size(); i ++) { if (!flag[i]) { return i; } } return nums.size() + 1; }};// Sample input: ./a.out numa_1 numa_2 numb_1 numb_2...int main(int argc, char * argv[]) { Solution so; vector<int> test; for (int i = 1; i < argc; i++) { test.push_back(atoi(argv[i])); } int re = so.firstMissingPositive(test); cout<<"re: "<<re<<endl; return 0;}
测试:./a.out -1 -1 -1 22 44结果:re: 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
- Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <p
- MyBatis:Parameter Maps collection does not contain value for 的问题解决
- Volecity模板引擎学习笔记<一>
- (java并发)ScheduledThreadPoolExcutor
- CString转int _ttoi() _tcstoul() Format ASSERT() Format的用法
- Leetcode First Missing Positive
- MySQL数据库查询操作
- 数据库事务
- Struts2学习笔记——Struts2与Spring整合
- NOIP 2013 积木大赛 贪心
- 简单的Gson转换json数据
- Redis开源代码读书笔记六(sds模块)
- java集合类图
- 数据库性能优化