LeetCode OJ:First Missing Positive (第一个丢失的正数)
2015-10-10 22:33
429 查看
在leetCode上做的第一个难度是hard的题,题目如下:
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.
关键是要实现0(N)的时间复杂度以及常数级别的空间复杂度,先贴上我写的函数,完全不能达到上面的要求,只能实现NlgN的时间复杂度:
由于达不到时间以及空间复杂度的要求,实在想不出来,我去看了下别人写的,现在由于vector可能会出现重复的数,我暂时不知带怎样去解决,只有先这样,回头有时间再回来填坑。
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.
关键是要实现0(N)的时间复杂度以及常数级别的空间复杂度,先贴上我写的函数,完全不能达到上面的要求,只能实现NlgN的时间复杂度:
class Solution { public: int firstMissingPositive(vector<int>& nums) { sort(nums.begin(), nums.end()); int sz = nums.size(); if(sz == 0) return 1; int index; for (index = 0; index < sz; index++){ if (nums[index] <= 0) continue; else break; } if (nums[index] != 1 || index == sz) return 1; //当没有正数的情况或正数的第一个数不是1的情况 while (index < sz){ if (nums[index + 1] != nums[index] && nums[index + 1] != nums[index] + 1) //两个判断主要是为了防止vector中重复的数字出现。 return nums[index] + 1; index++; } return nums[index] + 1; } };
由于达不到时间以及空间复杂度的要求,实在想不出来,我去看了下别人写的,现在由于vector可能会出现重复的数,我暂时不知带怎样去解决,只有先这样,回头有时间再回来填坑。
相关文章推荐
- 八,字符型变量
- 免费下载Sentinel-1雷达数据
- Java String类习题
- 前端基础内容读书笔记(一)
- 带你玩转Visual Studio——带你理解微软的预编译头技术
- ES6详解八:模块(Module)!
- 我写过的软件之OneWorld-大世界3
- 关于白盒测试的实验总结
- 没有Hyper-V服务,WP Emulator无法启动
- 【栈项目3 - 括号的匹配--第六周】
- 数据结构实践——字符串加密
- 最长公共字符串
- cyusb3014上位机同步传输与异步传输的实现
- [LeetCode][JavaScript]Word Pattern
- android学习第2篇:windows下android环境搭建:adt-bundle
- sicily. 放鸡蛋(输出情况总数+输出具体情况)
- ionic 安装
- MAC 下如何合并.cue 和 .bin 文件成为 .ISO
- 科研有方 ——科研准备和科研步骤
- EasyUI - LinkButton 按钮控件