代码1,对应力扣消失的数字,代码见下:
class Solution {
public:
int missingNumber(vector<int>& nums) {
unordered_map<int, int> hash;
for(int i=0; i<nums.size(); ++i){
hash[nums[i]] = 1;
}
for(int i=0; ;++i){
if(hash.find(i) == hash.end()){
return i;
}
}
}
};
代码2,对应力扣,缺失的第一个正数,代码见下
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
unordered_map<int, bool> hash;
for(int i=0; i<nums.size(); ++i){
hash[nums[i]] = true;
}
for(int i=1; ; ++i){
if(hash.find(i) == hash.end()){
return i;
}
}
return -1;
}
};
代码三,对应力扣寻找文件副本,代码见下:
class Solution {
public:
int findRepeatDocument(vector<int>& documents) {
unordered_map<int, bool> hash;
for(int i=0; i<documents.size(); ++i){
if(hash.find(documents[i]) != hash.end()){
return documents[i];
}
hash[documents[i]] = true;
}
return 0;
}
};
代码四,对应力扣,两数之和,代码见下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for(int i=0; i<nums.size(); ++i){
auto p = hash.find(target - nums[i]);
if(p != hash.end()){
return {i, p->second};
}
hash[nums[i]] = i;
}
return {};
}
};