目录(快速导航)
题目描述
视频讲解 https://www.bilibili.com/video/av66851964/
思路
代码
题目描述:
题目链接:https://leetcode-cn.com/problems/first-missing-positive/
给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
说明:
你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
视频讲解
https://www.bilibili.com/video/av66851964/
思路:
使用hash索引,每一个O(1)时间查找,总的不超过O(n).
挺简单的,直接使用C++ unordered_set 或者map也行。unordered_set
底层是hashtable。
代码:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
unordered_set<int> sets;
for (int num : nums)
sets.insert(num);
int i = 1;
while (true) {
if (sets.count(i++) == 0) {
return --i;
}
}
}
};