力扣hot100 chapter1
1. 两数之和
思路: 遍历数组中每个元素存到哈希表中,再查找表中是否有target-num[i]存在 有即找到
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash_table;
for (int i = 0; i < nums.size(); i++) {
auto it = hash_table.find(target - nums[i]);
if (it != hash_table.end()) {
return {it->second, i};
}
hash_table.insert({nums[i],i});
}
return {};
}
};
49. 字母异位词
题目链接
思路:
- 遍历所以的字符串
- 判断处理的字符串是否已经存在
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> hash_table;
vector<vector<string>> result;
//遍历每个字符串
int num = strs.size();
for (int i = 0; i < num; i++) {
//str1是排序后的字符串
string str1 = strs[i];
//str2代表初始字符串
string str2 = strs[i];
sort(str1.begin(),str1.end());
//如果还没有出现过该字符形式,插入一个新的
if (hash_table.find(str1) == hash_table.end()) {
hash_table.insert({str1,{str2}});
}
//已经出现过,追加到末尾
else {
hash_table[str1].push_back(str2);
}
}
//把哈希表中排好的结果放到目标数组中
for (auto it = hash_table.begin(); it != hash_table.end(); it++) {
result.push_back(it->second);
}
return result;
}
};
计数法: 参考leetcode题解
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> map;
for(string str:strs) {
int counts[26] = {0};
for(char c:str) {
counts[c-'a']++;
}
string key = "";
for(int i = 0;i<26;++i) {
if(counts[i]!=0) {
key.push_back(i+'a');
key.push_back(counts[i]);
}
}
map[key].push_back(str);
}
vector<vector<string>> res;
for(auto& p:map) {
res.push_back(p.second);
}
return res;
}
};
128. 最长连续序列
思路:
- 将数字存储到哈希集合中
- 找到连续序列的开头元素,即集合中没有n-1的元素n
- 遍历到n+1不存在 即序列结束
- 维护最长的结果长度
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> set;
for (int num: nums) {
set.insert(num);
}
int count = 0;
int res = 0;
for (auto it = set.begin(); it != set.end(); it++) {
//如果数字是开头数字 即没有前一个数字
int n = *it;
if (set.find(n-1) == set.end()) {
count = 1;
//如果有连续的数字
while (set.find(n+1) != set.end()) {
count++;
n = n + 1;
}
res = max(count,res);
}
}
return res;
}
};