Leecode Hot100 刷题笔记本-map(C++版)

66 阅读1分钟
  1. 1. 两数之和 简单
  2. 49. 字母异位词分组 中等
  3. 128. 最长连续序列 中等

1. 两数之和

Screen Shot 2023-08-06 at 10.33.04 AM.png

解法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 {};
    }
};
  • 时间复杂度: O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1) 地寻找 target - x
  • 空间复杂度:O(N),其中 N 是数组中的元素数量。主要为哈希表的开销

49. 字母异位词分组

Screen Shot 2023-08-06 at 11.03.20 AM.png

  • 由于互为字母异位词的两个字符串包含的字母相同,因此对两个字符串分别进行排序之后得到的字符串一定是相同的,故可以将排序之后的字符串作为哈希表的键。
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> mp;
        for (string& str: strs) {
            string key = str;
            sort(key.begin(), key.end());
            mp[key].emplace_back(str);
        }
        vector<vector<string>> ans;
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            ans.emplace_back(it->second);
        }
        return ans;
    }
};
  • 时间复杂度:O(nklogk),其中 n 是 strs 中的字符串的数量,k 是 strs 中的字符串的的最大长度, 需要遍历 n 个字符串,对于每个字符串需要 O(klogk) 的时间进行排序以及 O(1) 的时间更新哈希
  • 空间复杂度:O(nk), 其中 n 是 strs 中的字符串的数量,k 是 strs 中的字符串的的最大长度。需要用哈希表存储全部字符串