Leetcode First Missing Positive
来源:互联网 发布:监控电脑屏幕的软件 编辑:程序博客网 时间:2024/05/17 08:23
题意:找到第一个丢失的正数。
思路:使用hash实现O(1)的查找。
class Solution {public: int firstMissingPositive(vector<int>& nums) { map<int, bool> myhash; for(int i = 0; i < nums.size(); ++ i) { if(nums[i] > 0) { myhash[nums[i]] = true; } } int i = 1; while(true) { if(myhash[i] == false) return i; i ++; } }};
另一种思路仿照之前找重复的元素的方法,将元素放在其值和下标相对应的位置上,最后遍历整个数组,如果下标和值不能对应,则该值为缺失的值。
class Solution {public: int firstMissingPositive(vector<int>& nums) { for(int i = 0; i < nums.size(); i ++) { if(nums[i] == i + 1) continue; while(nums[i] <= nums.size() && nums[i] > 0 && nums[nums[i] - 1] != nums[i]) { int temp = nums[nums[i] - 1]; nums[nums[i] - 1] = nums[i]; nums[i] = temp; } } for(int i = 0; i < nums.size(); ++ i) { if(nums[i] != i + 1) return i + 1; } return nums.size() + 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
- Struts配置文件xml提示符设置
- perl模块 Compress::Raw::Lzma 的安装
- UVa OJ 10441 Catenyms
- Windows核心编程笔记(八)用户模式下的线程同步
- Subsets
- Leetcode First Missing Positive
- windows mysql 自动备份的几种方法
- LeetCode 370. Range Addition
- Java之Redis队列+Websocket+定时器实现跑马灯实时刷新
- T-SQL概述(常量变量运算符)
- Palindrome Linked List
- 【LeetCode】 319. Bulb Switcher
- 在行为树(Behavior Tree)中使用黑板(BlackBoard)
- 【LeetCode】 328. Odd Even Linked List