哈希表、映射、集合

哈希表、映射、集合

哈希

  • 哈希表(Hash table) ,也叫散列表,是根据关键码值(Key value)而直接进行访问的数据结构。
  • 它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。
  • 这个映射函数叫作散列函数(Hash Function),存放记录的数组叫作哈希表(或散列表)

工程实践

  • 电话号码簿
  • 用户信息表
  • 缓存(LRU Cache)
  • 键值对存储(Redis)

LeetCode实战例题

有效的字母异位词

class Solution {
public:
    bool isAnagram(string s, string t) {
        char mytable[26] = {0};
        for ( int i = 0; i < s.size(); i++){
            mytable[ s[i] - 'a' ] += 1;
        }
        for ( int i = 0;i < t.size(); i++){
            mytable[ t[i] - 'a' ] -= 1;
        }
        for ( int i = 0; i< 26; i++){
            if (mytable[i] != 0) return false;
        }
        return true;
        
    }
};

字母异位词分组

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;  
        int sub=0;  //结果vector的下标值
        string tmp; //临时string
        unordered_map<string,int> work; //判断排序后单词是否存在,即字母组成是否一致
        for(auto str:strs)
        {
            tmp=str;
            sort(tmp.begin(),tmp.end());
            if(work.count(tmp))
            {
               res[work[tmp]].push_back(str);
            }
            else
            {
                vector<string> vec(1,str);
                res.push_back(vec);
                work[tmp]=sub++;
            }
        }
        return res;
    }
};

两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
         vector<int> arr; 
        for(int i=0; i<nums.size(); i++) 
        {
            for(int j=i+1; j<nums.size(); j++)
            {
                if(target==nums[i]+nums[j]) 
                {
                    arr.push_back(i); 
                    arr.push_back(j); 
                }
            }
        }
        return arr;
    }
};

posted @ 2020-03-01 20:01  insist钢  阅读(365)  评论(0编辑  收藏  举报