Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

这道题让我们找缺失的首个正数,由于限定了 O(n) 的时间,所以一般的排序方法都不能用,最开始博主没有看到还限制了空间复杂度,所以想到了用 HashSet 来解,这个思路很简单,把所有的数都存入 HashSet 中,然后循环从1开始递增找数字,哪个数字找不到就返回哪个数字,如果一直找到了最大的数字(这里是 nums 数组的长度),则加1后返回结果 res,参见代码如下:

解法一:

// NOT constant space
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
unordered_set<int> st(nums.begin(), nums.end());
int res = , n = nums.size();
while (res <= n) {
if (!st.count(res)) return res;
++res;
}
return res;
}
};

但是上面的解法不是 O(1) 的空间复杂度,所以需要另想一种解法,既然不能建立新的数组,那么只能覆盖原有数组,思路是把1放在数组第一个位置 nums[0],2放在第二个位置 nums[1],即需要把 nums[i] 放在 nums[nums[i] - 1]上,遍历整个数组,如果 nums[i] != i + 1, 而 nums[i] 为整数且不大于n,另外 nums[i] 不等于 nums[nums[i] - 1] 的话,将两者位置调换,如果不满足上述条件直接跳过,最后再遍历一遍数组,如果对应位置上的数不正确则返回正确的数,参见代码如下:

解法二:

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for (int i = ; i < n; ++i) {
while (nums[i] > && nums[i] <= n && nums[nums[i] - ] != nums[i]) {
swap(nums[i], nums[nums[i] - ]);
}
}
for (int i = ; i < n; ++i) {
if (nums[i] != i + ) return i + ;
}
return n + ;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/41

类似题目:

Missing Number

Find the Duplicate Number

Find All Numbers Disappeared in an Array

Couples Holding Hands

参考资料:

https://leetcode.com/problems/first-missing-positive/

https://leetcode.com/problems/first-missing-positive/discuss/17071/My-short-c++-solution-O(1)-space-and-O(n)-time

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. npm淘宝镜像cnpm
  2. 【Python】列表各种操作
  3. Android 更改字体
  4. Newtonsoft.Json(C#处理json)
  5. memcache c++使用
  6. python如何控制数据库?
  7. SVN命令使用详解
  8. Js作用域与作用域链详解
  9. CSS如何实现图片上下垂直居中
  10. 浅析c语言中的变量(局部变量,外部变量,静态变量,寄存器变量)[转]
  11. Ubuntu Telnet 配置(openbsd-inetd)
  12. [Android]在Dagger 2中Activities和Subcomponents的多绑定(翻译)
  13. 网页版 treeview使用中遇到的问题
  14. 使用Flex图表组件
  15. WinEdt7.0 初试
  16. objective-c 中数据类型之中的一个 几何数据类型(CGPoint,CGSize,CGRect)
  17. Linux之 网卡发包、接包 error 、droped 情况
  18. ArcEngine GroupLayer监听图层改变
  19. React 入门实例教程(转载)
  20. Css3新属性:calc()

热门文章

  1. 【VSFTP服务】vsftpd文件传输协议
  2. [LeetCode#180]Consecutive Numbers
  3. java架构之路-(mysql底层原理)Mysql索引和查询引擎
  4. OpenGL入门1.3:着色器 GLSL
  5. WPF-控件模板
  6. deepin可视化程序打不开问题排查方法
  7. redux的详细介绍和使用!
  8. 「白帽黑客成长记」Windows提权基本原理(上)
  9. SAP S4HANA BP事务代码初始界面的ROLE和Grouping配置
  10. SQL行转列,列转行