Analysis of Leetcode Problem Solving Ideas (32) 228-234

  1. Summary interval
    Given an ordered integer array with no repeated elements, return the summary of the range of the array.

A very simple question, just go through it once

class Solution {
    
    
public:
    vector<string> summaryRanges(vector<int>& nums) 
    {
    
    
        vector<string> ans;

        for (int i = 0; i < nums.size(); i++)
        {
    
    
            string str = to_string(nums[i]);
            int pos = i;

            while (i < nums.size() - 1 && nums[i] + 1 == nums[i + 1]) 
            {
    
    
                i++; //数字连续
            }

            if (pos != i) //若有增加
            {
    
    
                str += "->" + to_string(nums[i]);
            }

            ans.push_back(str);
        }
        return ans;
    }
};


  1. Find the mode 2
    Given an array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Solved by Moore voting, if a mapping array is used directly, the space complexity does not meet the requirements

/*
时间复杂度为:O(n)
空间复杂度为:O(1)
*/
class Solution {
    
    
public:
    vector<int> majorityElement(vector<int>& nums) {
    
    
        int len = nums.size();
        vector<int>res, cands, cnts;
        if(len == 0){
    
    //没有元素,直接返回空数组
            return res;
        }
        cands.assign(2, nums[0]);
        cnts.assign(2, 0);
        //第1阶段 成对抵销
        for(auto num: nums){
    
    
            bool flag = false;
            for(int i = 0; i < cands.size(); ++i){
    
    
                if(num == cands[i]){
    
    
                    ++cnts[i];
                    flag = true;
                    break;
                }
            }
            if(!flag){
    
    
                bool flag2 = false;
                for(int j = 0; j < cands.size(); ++j){
    
    
                    if(cnts[j] == 0){
    
    
                        flag2 = true;
                        cands[j] = num;
                        cnts[j]++;
                    }
                }
                if(!flag2){
    
    
                    for(int j = 0; j < cnts.size(); ++j){
    
    
                        --cnts[j];
                    }
                }
            }
        }

        //第2阶段 计数 数目要超过三分之一
        cnts[0] = cnts[1] = 0;
        if(cands[0] == cands[1])
            cands.pop_back();
        for(auto num:nums){
    
    
            for(int i = 0; i < cands.size(); ++i){
    
    
                if(cands[i] == num){
    
    
                    ++cnts[i];
                    break;
                }
            }
        }
        for(int i = 0; i < cands.size(); ++i){
    
    
            if(cnts[i] > len / 3){
    
    
                res.push_back(cands[i]);
            }
        }
        return res;
    }
};

  1. Kth
    Smallest Element of Binary Search Tree Given a binary search tree, write a function kthSmallest to find the kth smallest element in it

The simplest way is to use recursion or iteration to arrange the middle order traversal, just take the kth element. Among them, iteration is better than recursion, because iteration finds the kth one and can stop returning immediately.


class Solution {
    
    

    int m_cnt = 0, m_ret = 0;

public:
    int kthSmallest(TreeNode* root, int k) 
    {
    
    
        __midOrder(root, k);
        return m_ret;
    }

private:
    void __midOrder(TreeNode *root, int k)
    {
    
    
        if (root == NULL) return;

        __midOrder(root->left, k);
        m_cnt++;
        if (m_cnt == k) m_ret = root->val;
        __midOrder(root->right, k);
    }
};

class Solution {
    
    

    int m_cnt = 0, m_ret = 0;

public:
    int kthSmallest(TreeNode* root, int k) 
    {
    
          
        return __midOrder(root, k);
    }

private:
    int __midOrder(TreeNode *root, int k)
    {
    
    
        stack<TreeNode *> s;
        TreeNode *cur = root;
        while (s.size() || cur)
        {
    
    
            while (cur)
            {
    
    
                s.push(cur);
                cur = cur->left;
            }
            cur = s.top();
            s.pop();
            m_cnt++;
            if (m_cnt == k) return cur->val;
            cur = cur->right;
        }
        return 0;
    }
};
  1. Power of 2 is a
    simple question
class Solution {
    
    
public:
    bool isPowerOfTwo(int n) {
    
    
        if (n <= 0) return false;
        while (n > 1)
        {
    
    
            if (n % 2 != 0)
                return false;
            else 
                n = n / 2;
        }
        return true;
    }
};
  1. Implement queues with stacks

Just like the previous queue, only one more stack is needed.

class MyQueue {
    
    
public:
    stack<int> inStack;
    stack<int> outStack;
    
    MyQueue() {
    
    

    }
    
    void push(int x) {
    
    
        inStack.push(x);
    }
    
    int pop() {
    
    
        cheak();
        int a=outStack.top();
        outStack.pop();
        return a;
    }

    int peek() {
    
    
        cheak();
        return outStack.top();
    }
    

    bool empty() {
    
    
        return inStack.empty()&&outStack.empty();
    }

    void cheak()
    {
    
    
        if(outStack.empty())
        {
    
    
            while(!inStack.empty())
            {
    
    
                outStack.push(inStack.top());
                inStack.pop();
            }

        }
    }
};

/*
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
  1. Number of number 1
    Given an integer n, count the number of occurrences of number 1 in all non-negative integers less than or equal to n.
    I is traversed from 1 to n, is 10-fold expansion of each iteration i:
    (n/(i*10))∗iindicates (i*10)the number of the bits.
    min(max((n mod (i*10)} )-i+1, 0), i)})Indicates the number of (i*10)1s in the digits that need extra digits .
class Solution {
    
    
public:
int countDigitOne(int n)
{
    
    
    int countr = 0;
    for (long long i = 1; i <= n; i *= 10) {
    
    
        long long divider = i * 10;
        countr += (n / divider) * i + min(max(n % divider - i + 1, 0LL), i);
    }
    return countr;
}
};

  1. Palindrome linked list
    Please judge whether a linked list is a palindrome linked list. Can you solve this problem with O(n) time complexity and O(1) space complexity?

The space complexity O(1) indicates that you cannot use stack storage or recursive search. Therefore, the approach here is to first use the fast and slow pointers to obtain the intermediate nodes, reverse the first half during the movement of the fast and slow pointers, and then compare the second half and the first half. Whether the values ​​are equal. Pay attention to the judgment of the parity of the intermediate node

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    bool isPalindrome(ListNode* head) {
    
    
        if(!head || !head->next)
            return 1;
        ListNode *fast = head, *slow = head;
        ListNode *p, *pre = NULL;
        while(fast && fast->next){
    
    
            p = slow;
            slow = slow->next;    //快慢遍历
            fast = fast->next->next;

            p->next = pre;  //翻转
            pre = p;
        }
        if(fast)  //奇数个节点时跳过中间节点
            slow = slow->next;

        while(p){
    
           //前半部分和后半部分比较
            if(p->val != slow->val)
                return 0;
            p = p->next;
            slow = slow->next;
        }
        return 1;
    }
};

Guess you like

Origin blog.csdn.net/u013354486/article/details/107096099