leetcode weekly summary

Keywords: ascii

What I learned this week

  1. In vector, sort() sorting problem of strings (compared by alphabet in order, the first priority is higher: ABC < ACB < BCA)
  2. Sort problem in array: (sort function scope is [begin, end], excluding the last bit)
    Static array: int a [10] = {9, 0, 1, 2, 3, 7, 4, 5, 8, 6}; sort (a, a + 10);
    (note that length is added to the next bit at the end of the array)
    vector: sort(heights.begin(), heights.end());
    (end() in vector represents the next digit of the last digit)
  3. string.substr (int start_ Usage of index, int length):
    When there are two parameters, the first one is the starting position, and the second one is the substring length eg: substr(0,5) gets the string with the length of 5 starting from the 0 bit in string s
    When a parameter is used, the string from the first bit to the end in string s is obtained by default from the specified start position to the end eg: substr(1))
  4. char string array ends with '\ 0', but string is a class with no character '\ 0' at the end
  5. Several methods to delete the last character of string in C + +:
    - str.pop_back();
    - str.erase(str.end() - 1);
    - str = str.substr(0, str.length() - 1);
  6. string.erase() usage
    (1) erase(pos,n); delete n characters from pos, for example, erase(0,1) is to delete the first character
    (2) erase(first, last); delete characters from first to last (first and last are iterators)
    (3) erase(pos); delete a character at pos (pos must be an iterator of type string string::iterator pos)
  7. The algorithm for finding prime numbers: eradorse sieve (a simplified and efficient algorithm for finding multiples of each number)
  8. On character transcoding:
    Char to int: generally use char - '0'
    Int to cha: generally use int + '0'
    (Note: char(4): convert 4 to '\ 4' instead of character '4', int('a '): convert string to corresponding ASCII code
    Therefore, when it comes to int/char conversion, it is better to use ± '0', where (char) should never be used
  9. Judge whether there is a value in vector: (STL) find
    vector<int>::iterator it = find(arr.begin(),arr.end(),res);
    if( it != arr.end()) / / value in array
    if( it == arr.end()) / / value not in array
  10. Freud's circular search algorithm (fast and slow pointer method / tortoise and rabbit pointer method)
    Principle: every step the rabbit takes, it approaches the tortoise to a node (in the direction of their movement). If there is, we will meet
    Used to determine whether a linked list has cycles

594, longest harmonic subsequence

class Solution {
public:
    int findLHS(vector<int>& nums) {
        unordered_map<int, int> hash;
        for(auto num:nums)
            hash[num]++;

        int res = 0;
        for(auto i : hash)
            //if(hash[i.first+1] != 0)
            if(hash.count(i.first+1))
                res = max(res, i.second + hash[i.first + 1]);

        return res;
    }
};

1160, spelling words

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        int res=0;
        int ch[26]={0};
        for(char c:chars)
            ch[c-'a']++;
        
        for(string word:words)
        {
            int wd[26]={0};
            for(char c:word)
                wd[c-'a']++;
            res+=word.size();
            for(char c:word)
            {
                if(ch[c-'a']<wd[c-'a'])
                {
                    res-=word.size();
                    break;
                }    
            }
        }
        return res;
    }
};

572, candy

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        int nums = candies.size();
        vector<int> hash(10000);
        for(int i = 0; i < nums; i++){
            hash[candies[i]]++;
        }

        int res = 0;
        for(int i = 0; i < 10000; i++){
            if(hash[i] >= 2) res++;
            else if(hash[i] == 1 && res < (nums/2) ) res++;
        }

        return min(nums/2, res);

    }
};

599 minimum index sum of common elements of two lists

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        unordered_map<string, int> hash;
        //unordered_map<string, unordered_map> hash;
        int i = 0;
        for(auto r1 : list1){
            
            i++;
            hash[r1] += i;
        }
        int j = 0;
        for(auto r2 : list2){
            
            j++;
            if(hash[r2] != 0){
                int tmp = -hash[r2];
                hash[r2] = tmp;
                hash[r2] -= j;
            } 
        }

        int min_res = INT_MAX;
        for(auto h:hash){
            if(h.second < 0)
                min_res = min(min_res, -h.second);
        }

        vector<string> arr_res;
        for(auto h:hash){
            if(-h.second == min_res)
                arr_res.push_back(h.first);
        }

        return arr_res;

    }
};

1078. Bigram participle

There are many small details about this question:

  1. char string array ends with '\ 0', but string is a class, and there is no character '\ 0' at the end (string ends with string length), so a '\ 0' is added to the string of this question as the end identifier
  2. Common operations in string:
    Delete: ear (iterator, Iterator);
    Add the character append (number, char) at the end;
class Solution {
public:
    vector<string> findOcurrences(string text, string first, string second) {
        vector<string> str_arr;
        string str;

    
        text.append(1,'\0');

        for(auto c : text){
            if(c == ' ' || c == '\0'){
                str_arr.push_back(str);
                str.erase (str.begin(), str.end());
            }
            else   
                str.append(1, c);
        }


        vector<string> res;
        for(int i = 1; i<str_arr.size(); i++){
            if(str_arr[i - 1] == first && str_arr[i] == second && i != str_arr.size() - 1)
            res.push_back(str_arr[i + 1]);
        } 

        return res;

    }
};

645. Wrong set

Note: the initialization of hash table and the specified operation are carried out separately to achieve the purpose

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        unordered_map<int, int> hash;
        for(int i = 0; i < nums.size();i++){
            hash[i] = 0;
        }

        for(auto num:nums){
            hash[num-1]++;
        }

        vector<int> res;
        for(auto h:hash){
            if(h.second == 2)
                res.push_back(h.first+1);
        }
        for(auto h:hash){
            if(h.second == 0)
                res.push_back(h.first+1);
        }


        return res;
    }
};

720, the longest word in the dictionary

const int MAX_NODE = 1000000 + 10;
const int CHARSET = 26;
int trie[MAX_NODE][CHARSET] = {0};
int ending[MAX_NODE] = {0};



int k = 1; // k is the node mark
void insert(string w){ //Insert a word in the Trie tree
    int len = w.size();
    int p = 0; // p is the dynamic node tag
    for(int i=0; i<len; i++){
        int c = w[i] - 'a';
        if(!trie[p][c]){
            trie[p][c] = k;
            k++;
        }
        p = trie[p][c];
    }
    ending[p] = 1;  //The ending array is a hash table, which is recorded as the node mark k of the terminating node
}

int search(string s){
    int len = s.size();
    int p = 0;
    for(int i=0; i<len; i++){
        int c = s[i] - 'a';
        if(!trie[p][c]) return 0;
        p = trie[p][c];
    }
    return ending[p] == 1;
}


class Solution {
public:
    string longestWord(vector<string>& words) {
        for(auto word:words){
            insert(word);
        }
        
        vector<string> res_arr;

        for(auto word:words){
            int length = word.size();
            bool flag = 1;
            while(length){
                if(!search(word.substr(0,length--))){
                    flag = 0;
                    break;      
                }
            }
            if(flag)
                res_arr.push_back(word);
        }
        
        int max_len = 0;
        for(auto s:res_arr){
            int s_len = s.size();
            max_len = max(max_len, s_len);
        }

        vector<string> res;
        for(auto s:res_arr){
            if(s.size() == max_len)
                res.push_back(s);
        }

        sort(res.begin(), res.end());
        

        return res[0];
    }
};

204 finding prime numbers

Eradosse method: efficient for loop to create hash table

class Solution {
public:
    int countPrimes(int n) {
    int count = 0;
    //Initial default all numbers are prime
    vector<bool> signs(n, true);
    for (int i = 2; i < n; i++) {
        if (signs[i]) {
            count++;
            for (int j = i + i; j < n; j += i) {
                //Exclude numbers that are not prime
                signs[j] = false;
            }
        }
    }
    return count;
	}
};

202 happy number

Happiness number: the sum of squares of each digit is 1, non-1 and can continue to cycle, and finally 1)
tips: in order to prevent infinite loop, you can use the array to memorize the values that have appeared, and reappear to indicate the dead loop

class Solution {
public:
    bool isHappy(int n) {
        unordered_map<char, int> hash;
        for(int i =0; i<10;i++){
            hash[i+'0'] = i*i;  //hash[char(i)] error -- (char) converts 4 to '\ 4' instead of '4';
          
        }
        
        int tacket = n;
        vector<int> arr;
        while(1){
            string num = to_string(tacket);
            int res = 0;
            for(auto c:num){
                res += hash[c];
            }
            if(res == 1) return 1;

            vector<int>::iterator it=find(arr.begin(),arr.end(),res);
            if(it != arr.end()) return 0; 
            else arr.push_back(res);
            tacket = res;
            
        }     
        
        return 0;
    }
};

Posted by textbox on Sun, 21 Jun 2020 18:17:39 -0700