Leetcod First Missing Positive,本算法使用hash表实现,此外注意到positive从1开始,而给出的数组至有多len(arr)个positive,而且有如下几种情况:
- 元素为负数,那么一定不会对计算positive产生影响
- 元素为正数,但是元素大于len(arr),此时也不会对结果有影响,因为此时在1到len(arr)这些数中一定会有空出的元素,因此大于len(arr)的元素可以直接忽略
- 元素在1到len(arr)之间,此时我们使用一张flag的数组记录对就的正整数i是否出现,若出现则记为true
最后,可以扫描flag数组,如果数组中有空缺,则第一个缺为最小正整数,如果没有空缺,最小正整数为len(arr) + 1。
相关代码如下,算法时间复杂度为o(n):
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
vector<bool> flag(nums.size() + 1, false);
for (int i = 0; i < nums.size(); i ++) {
if (nums[i] >= 0 && nums[i] <= nums.size()) {
flag[nums[i]] = true;
}
}
for (int i = 1; i < flag.size(); i ++) {
if (!flag[i]) {
return i;
}
}
return nums.size() + 1;
}
};
// Sample input: ./a.out numa_1 numa_2 numb_1 numb_2...
int main(int argc, char * argv[]) {
Solution so;
vector<int> test;
for (int i = 1; i < argc; i++) {
test.push_back(atoi(argv[i]));
}
int re = so.firstMissingPositive(test);
cout<<"re: "<<re<<endl;
return 0;
}
测试:./a.out -1 -1 -1 22 44
结果:re: 1