分析:
1.根据题意,首先需要将要数据选择一个合适的 数据结构模型。 因为是对应相关联,所以我们选择unordered_map
2.因为是一组数,所以用数组 ,将数值与数组下标对应起来
3.已知两数之和,从数组第一个数开始比较,确认余数是否在unordered_map中,如果存在,则使用key值取出其value;如果不在,则以key - value的形式将当前值和当前下表存入unordered_map,然后继续重复执行。
4.将要两个下标传入vector即可
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int,int> hash;
for (int i = 0; i < nums.size(); i ++ )
{
int another = target - nums[i];
if (hash.count(another))
{
res = vector<int>({hash[another], i});
break;
}
hash[nums[i]] = i;
}
return res;
}
};
分析:题意为把可以组成相同的字符串合并为一组
1.字符串可以转换为ASII码
2.先将要字符串排序,即abc , acb , cba, bac 等,经过排序后都是abc
3.使用哈希表将排序后的字符串作为key,后续相同的作为value存储
4.最后遍历哈希表即可解决,unordered_map<string,vector<string>>,key为排序后的字符串,value为原字符串
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> dict;
for (auto &str : strs)
{
string key = str;
sort(key.begin(), key.end());
dict[key].push_back(move(str));
}
vector<vector<string>> res;
for (auto i = dict.begin(); i != dict.end(); i ++ )
{
res.push_back(move(i -> second));
}
return res;
}
};