-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path41-firstMissingPositive.h
More file actions
72 lines (61 loc) · 1.34 KB
/
41-firstMissingPositive.h
File metadata and controls
72 lines (61 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#pragma once
#include <stdio.h>
#include <unordered_map>
#include <vector>
#include <bitset>
#include <stdlib.h>
#include <algorithm>
using namespace std;
/************************************************************************/
/*
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
*/
/************************************************************************/
class Solution41 {
public:
int firstMissingPositive(vector<int>& nums) {
int nMin = 0;
int val = INT_MAX;
unordered_map<int, int> mapTmp;
for (auto i = 0u; i < nums.size(); ++i)
{
if (nums[i] <= 0)
mapTmp[nums[i]] = 1;
else
mapTmp[nums[i]] = nums[i] + 1;
if (nums[i] < val)
{
nMin = i;
val = nums[i];
}
}
//
while (true)
{
auto it = mapTmp.find(val);
if (it != mapTmp.end()) return val;
val = it->second;
}
}
int firstMissingPositive1(vector<int>& nums) {
std::bitset<500000> bsTmp;
int v_min = INT_MAX;
int v_max = 0;
for (auto i = 0u; i < nums.size(); ++i)
{
if (nums[i] > 0 && nums[i] <= 5 * 10e5)
{
bsTmp.set(nums[i]);
v_max = max(v_max, nums[i]);
v_min = min(v_min, nums[i]);
}
}
if (v_min > 1) return 1;
for (auto i = 1; i < v_max; ++i)
{
if (!bsTmp.test(i)) return i;
}
return v_max + 1;
}
};