leetcode题解 数据结构-哈希表
数组中两个数的和为给定值
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int,int> mp;
for(int i = 0;i < nums.size(); i++)
mp[nums[i]] = i;
for(int i = 0;i < nums.size(); i++){
int u = nums[i];
int v = target - u;
if(mp.find(v) != mp.end() && i != mp[v]){
ans.push_back(mp[v]);
ans.push_back(i);
break;
}
}
return ans;
}
}
判断数组是否含有重复元素
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
map<int,int> mp;
for(int i = 0;i < nums.size(); i++){
if(mp.find(nums[i]) != mp.end())
return true;
mp[nums[i]] = 1;
}
return false;
}
};
最长和谐序列
class Solution {
public:
int findLHS(vector<int>& nums) {
map<int,int> mp;
for(int i = 0;i < nums.size(); i++)
mp[nums[i]] += 1;
int ans = 0;
for(auto it: mp){
int low = 0, high = 0;
int v = it.first;
if(mp.find(v-1) != mp.end())
low = mp[v-1];
if(mp.find(v+1) != mp.end())
high = mp[v+1];
if(low > 0)
ans = max(ans, it.second + low);
if(high > 0)
ans = max(ans, it.second + high);
}
return ans;
}
};
最长连续序列
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
map<int, int> mp;
for(int i = 0;i < nums.size(); i++)
mp[nums[i]] = 1;
int ans = 0;
for(auto it: mp){
int value = it.first, temp_ans = 1;
if(mp.find(value - 1) == mp.end()){
while(mp.find(value+1) != mp.end()){
value = value + 1;
temp_ans += 1;
}
}
if(ans < temp_ans)
ans = temp_ans;
}
return ans;
}
};