[Algorithm Series (3)]: Search

table of Contents

 

One, lookup table

1.1, algorithm application

349. Intersection of two arrays

350. The Intersection of Two Arrays II

242. Valid Letter Alien Words

202. Happy Number

290. Word Law

451. Sort according to frequency of characters


One, lookup table

The basic data structure considered is mainly divided into the following situations:

  • The first category: search for existence--set

For example: whether the element'a' exists, usually set: set. The set only stores the key, and does not need to correspond to its corresponding value. The keys in the set are not allowed to be repeated.

  • The second category: Find the correspondence (key-value correspondence) --dict

The element'a' appears several times: dict-->dictionary. The keys in the dict are not allowed to be repeated.

  • The third category: change the mapping relationship-map

Through the unified representation of the relationship mapping of the original sequence as other

1.1, algorithm application

349. Intersection of two arrays

  • Title description

Given two arrays nums, find the common elements of the two arrays.

如nums1 = [1,2,2,1],nums2 = [2,2]

结果为[2]
结果中每个元素只能出现一次
出现的顺序可以是任意的
  • Problem-solving ideas

Since each element only appears once, there is no need to pay attention to the number of times each element appears, just use the set data structure. Record the presence and absence of elements.

Record nums1 as a set, and judge whether the elements of nums2 are in the set. If so, put it in a public set, and the final public set is the result we want.

  • C++ algorithm implementation
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    set<int> set1(nums1.begin(),nums1.end());
    set<int> set2(nums2.begin(),nums2.end());

    vector<int> res;

    for(auto i=set1.begin();i!=set1.end();++i){
        if(set2.find(*i)!=set2.end()){
            res.push_back(*i);
        }
    }

    return res;
}

350. The Intersection of Two Arrays II

  • Title description

Given two arrays, write a function to calculate their intersection.

Example 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
  • Problem-solving ideas

The number of occurrences of an element is useful, so it is meaningful for the number of storage. Therefore, when choosing a data structure, you should choose the structure of dict and judge by comparison of dictionaries;

Record the frequency of each element at the same time.

Record the dictionary of num1, traverse nums2, and compare whether the key of nums of the dictionary of nums1 is greater than zero to make a judgment.

  • C++ algorithm implementation
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
    vector<int> res;
            map<int,int> temp;
            for(int i=0;i<nums1.size();i++)
            {
                temp[nums1[i]]++;
            }
            for(int i=0;i<nums2.size();i++)
            {
                if(temp[nums2[i]]>0)
                {
                    res.push_back(nums2[i]);
                    temp[nums2[i]]--;
                }
            }
            return res;
}

242. Valid Letter Alien Words

  • Title description

Given two strings s and t, write a function to determine whether t is an anagram of s.

示例1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false
  • Problem-solving ideas

Judging the ectopic word means judging whether the character string after the transformation position is the same as the original one, then not only the elements need to be stored, but also the number of elements needs to be recorded. You can select the data structure of the dict, store both the strings s and t in the dict, and then directly compare whether the two dicts are the same.

  • C++ algorithm implementation
bool isAnagram(string s, string t) {
    if (s.size() != t.size())
            {
                return false;
            }
            int cNum[26] = {0};
            for (int i = 0; i < s.size(); ++i)
            {
                cNum[s[i] - 'a']++;
            }
            for (int i = 0; i < t.size(); ++i)
            {
                if (cNum[t[i] - 'a'] == 0)
                {
                    return false;
                }
                else
                {
                    cNum[t[i] - 'a']--;
                }
            }
            return true;
}

202. Happy Number

  • Title description

Write an algorithm to determine whether a number is a "happy number".

A "happy number" is defined as: For a positive integer, every time the number is replaced by the sum of the squares of the numbers in each position, and then this process is repeated until the number becomes 1, or it may be an infinite loop but always changes Less than 1. If it can be changed to 1, then this number is a happy number.

示例: 
输入: 19
输出: true
解释: 
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
  • Problem-solving ideas

Only need to judge whether there is or not, and there is no need to record the number of times, so the data structure of set is used. Each time the summed number is appended, when the new summed value exists in the set, it returns false.

  • C++ algorithm implementation
bool isHappy(int n) {
    set<int> sets;
    while(n!=1){
        int sum=0;
        while(n>0){
            sum+=pow((n%10),2);
            n=n/10;
        }        
        if(sets.find(sum)!=sets.end()){
            return false;
        }

        sets.insert(sum);
        n=sum;

    }

    return true;
}

290. Word Law

  • Title description

Given a pattern and a string, determine whether the string conforms to the pattern

示例1:
输入: pattern = "abba", 
str = "dog cat cat dog"
输出: true

示例 2:
输入:pattern = "abba", 
str = "dog cat cat fish"
输出: false

示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false

示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
  • Problem-solving ideas

Corresponding to the value under the same index, such as dict1[index] = dict2[index], then we can create two new dictionaries, traverse the index to assign values ​​to the two new dictionaries, and compare the values.

  • C++ algorithm implementation
bool wordPattern(string pattern, string str) {
    int n = pattern.size();
    unordered_map<int, string> m;
    vector<string> vec;//保存单词
    string s;
    for(const auto &c : str){
        if(isspace(c)){
            vec.push_back(s);
            s.clear();
            continue;
        }
        s += c;
    }
    vec.push_back(s);
    if(n != vec.size()) return false;

    for(int i = 0; i < n; ++i){
        if(m.count(pattern[i])){
            if(m[pattern[i]] != vec[i]) return false;
        }else{
            for(auto v : m){//此处可以优化,多一个哈希表set就可以免去查找
                if(v.second == vec[i])  return false;
            }
            m[pattern[i]] = vec[i];
        }
    }
    return true;
}

451. Sort according to frequency of characters

  • Title description

Given two strings s and t, determine whether they are isomorphic. If the characters in s can be replaced to get t, then the two strings are isomorphic. All occurrences of characters must be replaced with another character while preserving the order of the characters. Two characters cannot be mapped to the same character, but the character can be mapped to itself.

示例 1:
输入: s = "egg", t = "add"
输出: true

示例 2:
输入: s = "foo", t = "bar"
输出: false

示例 3:
输入: s = "paper", t = "title"
输出: true
  • Problem-solving ideas

The idea is the same as the previous question. You can consider how to compare the differences by constructing two dicts, and you can also convert the differences into the same.

  • C++ algorithm implementation
string frequencySort(string s) {
    map<char,int> m;

    for(auto c:s){
        if(m.count(c)){
            m[c]++;
        }else{
            m[c]=1;
        }
    }

    vector<pair<char,int>> vec(m.begin(),m.end());

    sort(vec.begin(),vec.end(),[](const pair<char, int>& a, const pair<char, int>& b){return a.second>b.second;});
    string res="";
    for(auto it=vec.begin();it!=vec.end();++it){
        while(it->second>0){
            res+=it->first;
            it->second--;
        }
    }

    return res;
}

 

Guess you like

Origin blog.csdn.net/wxplol/article/details/108203123