两数之和(leetcode.1)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
注意点:
- 为什么要用哈希表,因为两数之和要判断当前位置所需要的另一个加数是否在之前遍历过的元素集合之中
- 遍历的元素值作为键,下标作为值存入哈希表中,因为哈希表就是找键的性能高
- 使用unordered_map作为哈希表
最长连续序列(leetcode.128)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> num_set;
// 去重
for(const int& num : nums){
num_set.insert(num);
}
int longestStreak = 0;
for(const int& num : num_set){
// 如果不存在num-1
if(!num_set.count(num-1)){
int currentNum = num;// 则num是开头元素
int currentStreak = 1;// 连续序列的初始长度置为1(因为存在num)
// 接下来从开头元素不断向后找连续的元素
while(num_set.count(currentNum + 1)){
currentNum += 1;
currentStreak += 1;
}
longestStreak = max(longestStreak,currentStreak);
}
}
return longestStreak;
}
};
字母异位词分组(leetcode.49)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> mp;
// 字母异位词的组成元素相同,可以排序后作为key存入map,value则为单词
for(string& str : strs){
string key = str;
sort(key.begin(),key.end());
mp[key].emplace_back(str);
}
vector<vector<string>> ans;
// 遍历map,将value存入结果数组中
for(auto it = mp.begin();it != mp.end(); it++){
ans.emplace_back(it->second);
}
return ans;
}
};