LeetCode题解之hash判重(一)

167 阅读1分钟

1.基本题目

1. 两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> maps;
        for(int i = 0;i < nums.size(); i ++)
        {
            int other = target - nums[i];
            if(maps.find(other) != maps.end())//没找到会返回end()迭代器,增删改查都是o(1)的
                return {maps[other],i};
            maps[nums[i]] = i;//把遍历过的数存入hash表:hash[值]=下标
        }
        return {};
    }
};

49. 字母异位词分组

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        //相当于是暴力做法吧:先对每个字符串排序,相同的就加到map里,最后遍历一次map得到答案
        //时间复杂度o(nklogk)
        vector<vector<string>> res;
        unordered_map<string, vector<string>> m;
        for(auto& x: strs)
        {
            auto tmp = x;
            sort(tmp.begin(), tmp.end());
            m[tmp].push_back(x);
        }
        for(auto& n: m)
        {
            res.push_back(n.second);
        }
        return res;
    }
};

剑指 Offer 50. 第一个只出现一次的字符

class Solution {
public:
    char firstUniqChar(string s) {
        map<char,int> count;
        for(auto c: s) count[c] ++;
        char res = ' ';
        for(auto c: s)
            if(count[c] == 1) {res = c; break;}
        return res;
    }
};

1207. 独一无二的出现次数

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        unordered_map<int, int> m;
        for(auto c : arr) m[c] ++;//转化为看map里面有没有重复数字:-5:2,6:1,-6:1
        unordered_map<int,int> nums(0);
        for(auto pair: m) nums[pair.second] ++;
        for(auto pair : nums)
            if(pair.second > 1) 
                return false;       
        return true;//都不return false才返回true
    }
};