Weekly notes of leetcode brushing questions -2021.11.21-2021.11.28

11.21-559. Maximum depth of n-ary tree

Problem surface

Given an N-ary tree, find its maximum depth.

The maximum depth is the total number of nodes on the longest path from the root node to the farthest leaf node.

N-ary tree input is represented by sequence traversal serialization, with each group of child nodes separated by null values (see example).

Source: LeetCode
Link: https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

thinking

There's nothing to say, dfs/bfs board problem.

main points

Graph theory dfs/bfs

code

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    int maxDepth(Node* root) {
        if (root==NULL)
            return 0;
        else{
            int res=0;
            for (auto node:root->children)
                res=max(res,maxDepth(node));
            res=res+1;
            return res;
        }
    }
};

Completion status

Independent completion

11.22-384. Scrambling arrays

Problem surface

Give you an integer array nums and design an algorithm to disrupt an array without duplicate elements.

Implement Solution class:

Solution(int[] nums) initializes the object with an integer array nums
int[] reset() resets the array to its initial state and returns
int[] shuffle() returns the result of random array scrambling

Source: LeetCode
Link: https://leetcode-cn.com/problems/shuffle-an-array
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

thinking

Maintain two pointers, i i i pointer and j j j pointer. i i i pointer from left to right, j j j pointer is [ i , n − 1 ] [i,n-1] Random pointer in the range [i,n − 1]. Every time i i i and j j Exchange of digital values pointed to by j.

main points

shuffle algorithm

code

class Solution {
public:
    vector<int> nums;
    vector<int> orig;
    Solution(vector<int>& nums) {
        this->nums=nums;
        this->orig.resize(nums.size());
        copy(nums.begin(),nums.end(),orig.begin());
    }
    
    vector<int> reset() {
        copy(orig.begin(),orig.end(),nums.begin());
        return nums;
    }
    
    vector<int> shuffle() {
        for(int i=0;i<nums.size();i++){
            int j=i+rand()%(nums.size()-i);
            swap(nums[i],nums[j]);
        }
        return nums;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(nums);
 * vector<int> param_1 = obj->reset();
 * vector<int> param_2 = obj->shuffle();
 */

Completion status

With the help of problem solving

11.23-859. Intimacy string

Problem surface

Give you two strings S and goal. As long as we can get the result equal to goal by exchanging the two letters in s, we will return true; Otherwise, false is returned.

The definition of exchange letter is: take two subscripts I and J (subscript starts from 0) and meet I= j. The characters at s[i] and s[j] are then exchanged.

For example, exchanging elements of subscript 0 and subscript 2 in "abcd" can generate "cbad".

Source: LeetCode
Link: https://leetcode-cn.com/problems/buddy-strings
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

thinking

This question needs to count 26 letters and the number of times each letter appears. But there are many details to consider: if the two strings are different in length, false is returned directly. If two strings are the same, you need to consider whether a character has appeared twice. If the two strings are different, you need to consider whether there are and only 2 characters different.

code

class Solution {
public:
    int cnts[26];
    int cntg[26];
    bool buddyStrings(string s, string goal) {
        if(s.size()!=goal.size())
            return false;
        int len=s.size();
        int sum=0;
        for(int i=0;i<len;i++){
            cntg[goal[i]-'a']++;
            cnts[s[i]-'a']++;
            if(goal[i]!=s[i])
                sum++;
        }
        bool swapflag=false;
        for(int i=0;i<26;i++)
            if (cnts[i]>=2){
                swapflag=true;
                break;
            }
        for(int i=0;i<26;i++)
            if(cnts[i]!=cntg[i])
                return false;
        if(sum==2||sum==0&&swapflag)
            return true;
        else
            return false;
    }
};

Completion status

Independent completion

11.24-423. Reconstruction of figures from English

Problem surface

Give you a string s, which contains several numbers (0-9) represented by English words in disordered alphabetical order. Returns the original number in ascending order

thinking

Count. The number of z is 0; The number of w is 2; The number of u is 4; The number of x is 6; The number of g is 8. These five numbers can be reconstructed directly. next
, 3 and 8 have h; Both 5 and 4 have f; Both 7 and 6 have s, and these can also be rebuilt. 1. 0, 2 and 4 have o, rebuild 1; 5. 6, 8 and 9 have i, reconstruction 9.

code

class Solution {
public:
    int nums[10];
    int st[26];
    string res;
    string originalDigits(string s) {
        int len=s.size();
        for(int i=0;i<len;i++)
            st[s[i]-'a']++;
        nums[0]=st['z'-'a'];
        nums[2]=st['w'-'a'];
        nums[4]=st['u'-'a'];
        nums[6] = st['x'-'a'];
        nums[8]=st['g'-'a'];
        nums[3] = st['h'-'a'] - nums[8];
        nums[5] = st['f'-'a'] - nums[4];
        nums[7] = st['s'-'a'] - nums[6];

        nums[1] = st['o'-'a'] - nums[0] - nums[2] - nums[4];

        nums[9] = st['i'-'a'] - nums[5] - nums[6] - nums[8];
        for (int i = 0; i < 10; ++i) {
            for (int j = 0; j < nums[i]; ++j) {
                res += char(i + '0');
            }
        }
        return res;
    }
};

Completion status

Completed independently, but not the optimal solution.

11.25-458. Poor little pig

Problem surface

There are buckets of liquid, one of which contains poison, and the rest is water. They all look the same from the outside. In order to find out which bucket contains poison, you can feed some pigs and judge by observing whether the pigs will die. Unfortunately, you only have minutes to test minutes to determine which barrel of liquid is toxic.

The rules for feeding pigs are as follows:

Several live pigs were selected for feeding
Piglets can be allowed to drink any number of buckets of water at the same time, and the process does not take time.
The piglet must have a minute to die cooling time after drinking water. During this time, you can only observe, not continue to feed pigs.
After minutes to die, all the pigs that drank the poison will die and all the other pigs will survive.
Repeat this process until time runs out.
Give you the number of buckets, minutesToDie and minutesToTest, and return the minimum number of pigs required to determine which bucket is toxic within a specified time.

Source: LeetCode
Link: https://leetcode-cn.com/problems/poor-pigs
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

thinking

Push formula: number of test rounds k = m i n u t e s T o T e s t / m i n u t e s T o D i e k=minutesToTest/minutesToDie k=minutesToTest/minutesToDie
Number of piglets r e s = ⌈ ( l o g 2 ( b u c k e t s ) / l o g 2 ( k ) ) ⌉ res=\lceil (log_2(buckets)/log_2(k)) \rceil res=⌈(log2​(buckets)/log2​(k))⌉

main points

Number theory. Hexadecimal representation. State compression

code

class Solution {
public:
    int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        int k=minutesToTest/minutesToDie;
        return ceil(log(buckets)/log(k+1));
    }
};

Completion status

With the help of problem solving

11.26-700. Search in binary search tree

Problem surface

Given the root node and a value of a binary search tree (BST). You need to find the node whose node value is equal to the given value in the BST. Returns the subtree with this node as the root. NULL if the node does not exist.

thinking

There's nothing to say, dfs.

code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        if(root==NULL)
            return NULL;
        TreeNode* res=NULL;
        if (root->val>val)
            res=searchBST(root->left,val);
        if(root->val==val)
            res=root;
        if(root->val<val)
            res=searchBST(root->right,val);
        return res;

    }
};

Completion status

Independent completion

11.27-519. Random flip matrix

Problem surface

Give you a binary matrix of m x n, and all values are initialized to 0. Please design an algorithm, randomly select a subscript (i, j) that satisfies matrix[i][j] == 0, and change its value to 1. All subscripts (i, j) satisfying matrix[i][j] == 0 shall be equally selected.

Minimize calls to built-in random functions and optimize time and space complexity.

Implement the Solution class:

Solution(int m, int n) initializes the object with the sizes m and N of the binary matrix
int[] flip() returns a random subscript [i, j] satisfying matrix[i][j] == 0, and changes the value in its corresponding lattice to 1
void reset() resets all values in the matrix to 0

Source: LeetCode
Link: https://leetcode-cn.com/problems/random-flip-matrix
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

thinking

Use the hash table to store 1 bit in the matrix. Second order of matrix i , j i,j i. One for bit J k k k represents. k = i ∗ n + j k=i*n+j k=i∗n+j. The rest of the operation is similar to the shuffle algorithm.

main points

Hash table. The subscript of a matrix is represented by a number. shuffle algorithm

code

class Solution {
public:
    int m,n,cnt;
    map<int,int> st;

    Solution(int m, int n) {
        this->m=m;
        this->n=n;
        this->cnt=m*n;
    }
    
    vector<int> flip() {
        int x=rand()%cnt;
        vector<int> ans;
        cnt--;
        if(!st.count(x))
            ans={x/n,x%n};
        else
            ans={st[x]/n,st[x]%n};
        if(st.count(cnt))
            st[x]=st[cnt];
        else
            st[x]=cnt;
        return ans;
    }
    
    void reset() {
        cnt=m*n;
        st.clear();
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(m, n);
 * vector<int> param_1 = obj->flip();
 * obj->reset();
 */

Completion status

Read the solution. And after reading the problem solution, I remembered that I had done a problem of shuffling algorithm a few days ago. Sure enough, it's easy to see before and forget after.

Tags: Algorithm data structure leetcode

Posted on Sun, 28 Nov 2021 16:45:05 -0500 by dan231