Ten thousand people and one thousand problems plan-39

Keywords: Algorithm leetcode

preface

The front is the solution given by brother hero today. The back binary tree is your own content. Just look at it according to your own needs

Recommended community: ten thousand people and one thousand questions

Today's solution

The number of statistical digits is even

Idea:
According to the division by 10 method, the corresponding digits of the number can be obtained (the while block in the code)
count needs to be initialized before each number traversal
Even number:% 2 is 0, 0 is even number; Not 0: odd

class Solution {
public:
    int findNumbers(vector<int>& nums) {
        int count, res = 0;
        for(int i =0; i<nums.size(); ++i) {
            count = 0;
            while(nums[i]!=0) {
                ++count;
                nums[i] /= 10;
            }
            if(count % 2 == 0) {
                ++res;
            }
        }
        return res;
    }
};

A single element in an ordered array

Idea: binary search, search all even indexes until the first index with different subsequent elements is encountered
If it is out of order, it can be solved by bit operation. It is the optimal solution. I'm too lazy to post code. The previous problem solution is

class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int left = 0, right = nums.size()-1;
        while(left < right) {
            int mid = left + (right-left)/2;
            if(mid %2 == 1) {
                --mid;
            }
            if(nums[mid] == nums[mid + 1]) {
                left = mid + 2;
            }else right = mid;
        }
        return nums[left];
    }
};

Sword finger Offer 21. Adjust the array order so that odd numbers precede even numbers

Idea: in the code comments

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int left = 0;
        int right = nums.size() - 1;
        // A number cannot be both odd and even, so the termination condition of the push cycle is left == right
        // The array in good order is odd before the left pointer and even after the right pointer
        while(left < right) {
            // left find even number
            while(left < right && nums[left] % 2 != 0) {
                ++left;
            }
            // right find odd number
            while(left < right && nums[right] % 2 == 0) {
                --right;
            }
            // Swap the even number to the left of left and the odd number to the right of right
            if(left < right) {
                swap(nums[left], nums[right]);
            }
        }
        // When left and right coincide, the array sorting is completed
        return nums;
    }
};

Valid Letter ectopic words

Idea: open a new 26 size array to store the types of letters
The for loop iterates over two strings to see if their letters appear the same number of times

class Solution {
public:
    bool isAnagram(string s, string t) {
        int record[26] = {0};
        for(int i=0; i<s.size(); i++) {
            record[s[i] - 'a']++;
        }
        for(int i=0; i<t.size(); i++) {
            record[t[i] - 'a']--;
        }
        for(int i=0; i<26; i++) {
            if(record[i] != 0) {
                return false;
            }
        }
        return true;
    }
};

Idea: this question requires us to return the penultimate position after sorting the array
1. Use heap or priority queue_ queue
2. Maintain a K-size small top heap, and the top of the heap is the k-th largest number
3. When the size of the heap is already k, you need to judge directly with the top of the heap to decide whether to add it to the heap
At present, I will not implement heap or priority queue by hand

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int>> pq;
        for (auto n : nums) {
            if (pq.size() == k && pq.top() >= n) continue;
            if (pq.size() == k) {
                pq.pop();
            }
            pq.push(n);
        }
        return pq.top();
    }
};

Missing number

Idea: use the hash set to insert the data in num [i] into the set set to see if the number 0~n has appeared in the set set. If it has not appeared, it is the lost number

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        unordered_set<int> Set;
        int n = nums.size();
        for(int i=0; i<n; i++) {
            Set.insert(nums[i]);
        }
        int missing = -1;
        for(int i=0; i<=n; i++) {
            if(Set.count(i) == 0) {
                missing = i;
                break;
            }
        }
        return missing;
    }
};

Find different

Idea: the string t is randomly rearranged by the string s, and then a letter is added in a random position.
Please find the letter added in t.

class Solution {
public:
    char findTheDifference(string s, string t) {
        int res = 0;
        for(auto &i : t) {
            res += i;
        
        for(auto &i : s) {
            res -= i;
        }
        return res;
    }
};

balanced binary tree

Idea: use stack and iterative method

class Solution {
public:
    int getDepth(TreeNode* cur) {
        stack<TreeNode*> sk;
        if(cur != nullptr) sk.push(cur);
        int res = 0;
        int depth = 0;
        while(!sk.empty()) {
            TreeNode* node = sk.top();
            if(node != nullptr) {
                //sk.top();
                sk.pop();
                sk.push(node);
                sk.push(nullptr);
                ++depth;
                if(node->left) sk.push(node->left);
                if(node->right) sk.push(node->right);
            }else {
                sk.pop();
                node = sk.top();
                sk.pop();
                --depth;
            }
            res = res > depth ? res : depth;
        }
        return res;
    }
    bool isBalanced(TreeNode* root) {
        stack<TreeNode*> sk;
        if(root == nullptr) return true;
        sk.push(root);
        while(!sk.empty()) {
            TreeNode* node = sk.top();
            sk.pop();
            if(abs(getDepth(node->left) - getDepth(node->right)) > 1) {
                return false;
            }
            if(node->left) sk.push(node->left);
            if(node->right) sk.push(node->right);
        }
        return true;
    }
};

All paths of binary tree

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        stack<TreeNode*> treeSk;
        stack<string>  pathSk;
        vector<string> res;
        if(root == nullptr) return res;
        treeSk.push(root);
        pathSk.push(to_string(root->val));
        
        while(!treeSk.empty()) {
            TreeNode* node = treeSk.top();
            treeSk.pop();
            string path = pathSk.top();
            pathSk.pop();

            if(node->left == nullptr && node->right == nullptr) {
                res.push_back(path);
            }

            if(node->left) {
                treeSk.push(node->left);
                pathSk.push(path + "->" + to_string(node->left->val));
            }

            if(node->right) {
                treeSk.push(node->right);
                pathSk.push(path + "->" + to_string(node->right->val));
            }
        }
        return res;
    }
};

Sum of left leaves

Idea: both recursive and iterative methods can be done, but the main thing is to understand the topic
The meaning of this question is: if the left node is not empty and the left node has no left and right children, then the node is a left leaf. It is impossible to judge whether the current node is a left leaf. You must judge whether its left child is a left leaf through the node's parent node.

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        stack<TreeNode*> sk;
        if(root == nullptr) return 0;
        sk.push(root);
        int res = 0;
        
        while(!sk.empty()) {
            TreeNode* node = sk.top();
            sk.pop();
            if(node->left != nullptr && node->left->left == nullptr && node->left->right == nullptr) {
                res += node->left->val;
            }
            if(node->left) sk.push(node->left);
            if(node->right) sk.push(node->right);
        }
        return res;
    }
};

Find the value in the lower left corner of the tree

Idea: use sequence traversal to find the value of the first leaf node in the last line

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> que;
        if(root == nullptr) return 0;
        que.push(root);
        int res = 0;
        while(!que.empty()) {
            int size = que.size();
            for(int i=0; i<size; ++i) {
                TreeNode* node = que.front();
                que.pop();
                if(i == 0) res = node->val;
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
        }
        return res;
    }
};

Path sum

Idea: it's all in the notes

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        //pair structure is used to store node pointer and path sum
        stack<pair<TreeNode*, int>> sk;
        if(root == nullptr) return false;
        sk.push(pair<TreeNode*, int> (root, root->val));
        while(!sk.empty()) {
            pair<TreeNode*, int> node = sk.top();
            sk.pop();

            //If the leaf node is found and the sum of paths is equal to the sum of targets
            //if(pair<TreeNode*, int> (node, node->val))
            if(!node.first->left && !node.first->right && node.second == targetSum) {
                return true;
            }
			//Press in the left node and record the path and
            if(node.first->left) {
                sk.push(pair<TreeNode*, int> (node.first->left, node.second + node.first->left->val));
            }
            //Press in the right node and record the path and
            if(node.first->right) {
                sk.push(pair<TreeNode*, int> (node.first->right, node.second + node.first->right->val));
            }
        }
        return false;
    }
};

Posted by stan801003 on Sun, 28 Nov 2021 03:27:06 -0800