[LeetCode] First Missing Positive

41. First Missing Positive

Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
bool check[500002] {false,};
public:
int firstMissingPositive(vector<int>& nums) {
int res = 1;
for(auto& n : nums) {
if(1 <= n and n <= 500000) check[n] = true;
while(check[res]) res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/first-missing-positive/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.