Hash Table

1. Two Sum


Given an array of integers, return  indices  of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
两层遍历时间复杂度为O(n^2),考虑使用unordered_map。以number[i]作为key,i作为value。如果sum-number[i]存在,则把number[i]和sum-number[i]对应的value作为结果输出;如果sum-number[i]不存在,则存入Hash Table。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> m;
        vector<int> result;
        for(int i=0;i<nums.size();i++){
            int complement=target-nums[i];
            if (m.find(complement)!=m.end() && m[complement] != i){
                result.push_back(i);
                result.push_back(m[complement]);
                break;
            }
            m[nums[i]]=i;
        }
        return result;
    }
};


3. Longest Substring Without Repeating Characters


Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

建立一个长度为128的整型数组map,用于存储每个字符出现的次数。利用双指针begin和end对字符串进行遍历,用end遍历时,每次把map[s[end]]加1,表示把s[end]加入子串中。当s[end]已存在于map中时,count++表示子串中已出现重复字符,此时开始从begin遍历。用begin遍历时,如果s[end]已存在于map中,则map[s[end]]减1,表示从子串中去掉s[end],同时count--,表示子串中已去除重复字符串。最后比较现在最大子串长度d与end-begin大小,将较大值存入d。直到end指向字符串尾时停止。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> map(128,0);
        int counter=0,begin=0,end=0,d=0;
        while(end<s.size()){
            if(map[s[end++]]++>0) counter++;
            while(counter>0) if(map[s[begin++]]-->1) counter--;
            d=max(d,end-begin);
        }
        return d;
    }
};


30. Substring with Concatenation of All Words


You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s"barfoothefoobarman"
words["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

寻找恰好包含所有给定等长单词的子串位置。思路是用hash map存储各单词,然后从s串串首开始遍历,并用另一个hash map存储遍历过的单词,当子串中单词全部被s串包含时,记录起始位置到数组。

class Solution {                                                                                                  
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        unordered_map<string,int> counts;
        for(string word:words)
            counts[word]++;
        int n=s.size(),num=words.size(),len=words[0].size();
        vector<int> index;
        for(int i=0;i<n-num*len+1;i++){
            unordered_map<string,int> seen;
            int j=0;
            for(;j<num;j++){
                string word=s.substr(i+j*len,len);
                if(counts.find(word)!=counts.end()){
                    seen[word]++;
                    if(seen[word]>counts[word])
                        break;
                }
                else break;
            }
            if(j==num) index.push_back(i);
        }
        return index;
    }
};


36. Valid Sudoku


Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

判断数独是否合法。需要用三个数组row,col,area分别用于存储每行、每列、每个九宫格是否已经填入某个指定的数字。遍历board中每一个数字,如果所在row,col,area未填入该元素,则将其赋值为true,如果所在row,col或area已经填入该数字,则返回false。board中数字全部遍历完则返回true。

class Solution {                                                                                                 
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        const int cnt=9;
        bool row[cnt][cnt]={false};
        bool col[cnt][cnt]={false};
        bool area[cnt][cnt]={false};
        for(int r=0;r<board.size();r++){
            for(int c=0;c<board[r].size();c++){
                if(!isdigit(board[r][c])) continue;
                    int num=board[r][c]-'0'-1;
                    if(row[r][num]==true){
                        return false;
                    }
                    row[r][num]=true;
                    if(col[c][num]==true){
                        return false;
                    }
                    col[c][num]=true;
                    int temp=(r/3)*3+(c/3);
                    if(area[temp][num]==true){
                        return false;
                    }
                    area[temp][num]=true;
                
            }
        }
        return true;
    }
};


49. Group Anagrams


Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
将字母组成相同的单词归类。使用hash map,把单词按照字母组成存入key-value对中,再按照key遍历hash map,存储结果。
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string,vector<string>> mp;
        for(string s:strs){
            string t=s;
            sort(t.begin(),t.end());
            mp[t].push_back(s);
        }
        vector<vector<string>> anagrams;
        for(auto m:mp){
            vector<string> anagram(m.second.begin(),m.second.end());
            anagrams.push_back(anagram);
        }
        return anagrams;
    }
};














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值