Prepare for the second test, three questions a day, Day17

Posted by Victorm on Mon, 24 Jan 2022 07:14:16 +0100

Prepare for the second test, three questions a day

Topic 1: minimum insertion times of balanced bracket string

Give you a parenthesized string s, which contains only the characters' ('and'). A parenthesized string is called balanced when it satisfies:

Any left parenthesis' ('must correspond to two consecutive right parentheses').
The left parenthesis' ('must precede the corresponding two consecutive right parentheses')'.
For example, "())", "()) (())" and "(()) ())" are balanced, and "() ()", "())" and "(())" are unbalanced.

You can insert the characters' ('and') 'anywhere to balance the string.

Please return the minimum number of inserts for s balance.

Example 1:

Input: s = "(())"
Output: 1
Explanation: the second left parenthesis has two matching right parentheses, but the first left parenthesis has only one right parenthesis. We need to add an extra '()' at the end of the string to make the string into a balanced string "(())".
Example 2:

Input: s = "())"
Output: 0
Explanation: the string has been balanced.
Example 3:

Input: s = "()"
Output: 3
Explanation: Add '(' to match the first ')' and then add ')' to match the last '('.
Example 4:

Input: s = "("
Output: 12
Explanation: add 12 ')' to get the balanced string.
Example 5:

Input: s = ")"
Output: 5
Explanation: add 4 '(' at the beginning and 1 ')' at the end of the string, and the string becomes a balanced string "((())".

Tips:

1 <= s.length <= 10^5
s contains only '(' and ').

Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-insertions-to-balance-a-parentheses-string

class Solution {
public:
    int minInsertions(string s) {
        //If one needs a right parenthesis, such as "()", the demand for the right parenthesis is 1
        //Two records the demand for two right parentheses. For example (()), two are required
        int one=0,two=0;
        for(char c:s){
            //An open parenthesis needs two right parentheses to match
            if(c=='('){
                two+=2;
                //If the currently required closing parentheses are odd, you need to
                if(two%2==1){
                    //Divide the demand for right parentheses into odd ones and even ones (remember to record even numbers at the end of two)
                    one++;
                    two--;
                }
            }
            //If the current is a closing bracket, the number of required closing brackets is reduced by one
            if(c==')'){
                two--;
                //There are too many right parentheses at present. You need to add an left parenthesis. If another left parenthesis corresponds to two right parentheses, you also need to add a right parenthesis
                if(two==-1){
                    one++;
                    two=1;
                }
            }
        }
        return one+two;
    }
};

Topic 2: merging binary trees

Given two binary trees, imagine that when you overlay one of them on the other, some nodes of the two binary trees will overlap.

You need to merge them into a new binary tree. The merging rule is that if two nodes overlap, their values are added as the new value after node merging. Otherwise, the node that is not NULL will be directly used as the node of the new binary tree.

Example 1:

Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/
4 5
/ \ \
5 4 7
Note: the merge must start at the root node of both trees.

Source: LeetCode
Link: https://leetcode-cn.com/problems/merge-two-binary-trees

/**
 * 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* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if(root1==nullptr) return root2;
        if(root2==nullptr) return root1;
        root1->val=root1->val+root2->val;
        root1->left=mergeTrees(root1->left,root2->left);
        root1->right=mergeTrees(root1->right,root2->right);
         return root1;
    }
};

Topic 3: most elements

Given an array of size n, find most of its elements. Most elements refer to elements that appear more than ⌊ n/2 ⌋ in the array.

You can assume that the array is non empty and that there are always many elements in a given array.

Example 1:

Input: [3,2,3]
Output: 3
Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

Advanced:

This paper attempts to design an algorithm with time complexity O(n) and space complexity O(1) to solve this problem.

Source: LeetCode
Link: https://leetcode-cn.com/problems/majority-element

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count=1;
        //Sort first
        sort(nums.begin(),nums.end());
         int n=nums[0],m=nums.size();
         //Judge the number of occurrences of the current element. If it exceeds num Size (), it is the majority element
        for(int i=1;i<m;i++){
            if(nums[i]==n){
                count++;
                if(count>nums.size()/2){
                return nums[i];
            }
            //Record the next element and judge
            }else{
                n=nums[i];
            }  
        }
        return nums[m-1];
    }
};

Topics: Algorithm leetcode