First Missing Positive
2016-07-21 15:12
183 查看
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.
Analyse:
1. Newest method: 0ms
2. Old method
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.
Analyse:
1. Newest method: 0ms
class Solution { public: int firstMissingPositive(vector<int>& nums) { if(nums.empty()) return 1; nums.push_back(-1); for(int i = 0; i < nums.size(); i++){ while(nums[i] > 0 && nums[i] < nums.size() && i < nums.size()) { if(nums[i] != i && nums[i] != nums[nums[i]]) swap(nums[nums[i]], nums[i]); else i++; } } for(int i = 1; i < nums.size(); i++){ if(nums[i] != i) return i; } return nums.size(); } };
2. Old method
class Solution { public: // Create a new vector of size nums.size() // Ignore the negative values and values larger than nums.size() // Put corresponding numbers in the array // Scan the array for the second time int firstMissingPositive(vector<int>& nums) { if(nums.empty()) return 1; int n = nums.size(); vector<int> temp(n + 1, 0); // Index start from 0 for(int i = 0; i < nums.size(); i++){ if(nums[i] < 0 || nums[i] > n) continue; temp[nums[i]] = nums[i]; } for(int i = 1; i <= n + 1; i++){ if(temp[i] == 0) return i; } return n + 1; } };
相关文章推荐
- 使用java发送邮件
- win7 exe 修改程序内存使用2G上限问题
- String,StringBuilder,StringBuffer
- https://jitpack.io
- c++实现字符串回文判断
- Android保存数据到SharedPreferences
- 顺序查找
- 想要惊艳面试官?你一张嘴就输了
- 关于java应用MD5校验文件和linux下md5Linux校验文件结果一致问题。
- 博优商业管理系统ASA数据库“File is shorter than expected -- transaction rolled back”错误修复
- ACM暑期集训——专题一[DFS]
- iOS备忘录之图标和启动页尺寸
- 浅析人脸检测之Haar分类器方法:Haar特征、积分图、 AdaBoost 、级联
- [Ubuntu] 编辑器Sublime
- UIScrollView、UIPageControl的属性总结
- LNMP一键安装脚本
- 委托
- Scala spark mongodb
- POJ1154
- 训练之搜索约会2