Analysis of Leetcode Problem Solving Ideas (34) 242-264

  1. Valid letter dysphorisms
    Given two strings s and t, write a function to determine whether t is a letter dysphorism of s.

This question is easy to solve with hash table or sorting

class Solution {
    
    
public:
    bool isAnagram(string s, string t) {
    
    
        if(s.size() != t.size())
            return false;
            
        int hash[26]={
    
    0};       //构建哈希数组
        for(auto n:s)
            hash[n-'a']++;
        for(auto n:t)
            hash[n-'a']--;
        for(int i=0;i<26;i++)
            if(hash[i]!=0)   return false;          //如果两数组不完全相等
        return true;
    }
};


  1. All paths
    of a binary tree Given a binary tree, return all paths from the root node to the leaf nodes.

Solve it recursively

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
    vector<string> ret;
public:
    vector<string> binaryTreePaths(TreeNode* root) {
    
    
        if (root == NULL) return ret;
        string str = to_string(root->val);
        PrintPath(str, root);
        return ret;
    }

    void PrintPath(string str, TreeNode *node)
    {
    
    
        if (node == NULL || (node->left == NULL && node->right == NULL)) 
        {
    
    
            ret.push_back(str);    
            return;
        }
        
        if (node->left != NULL)
        {
    
    
            string s = str + "->" + to_string(node->left->val);
            PrintPath(s, node->left);
        }
        if (node->right != NULL)
        {
    
    
            str += "->" + to_string(node->right->val);
            PrintPath(str, node->right);           
        }     
    }
};
  1. Sum
    given a non-negative integer num, the numbers on the various bits repeatedly added until the result is a number.

The simplest method is to solve it directly without stopping iterating. A better approach is to use abcd = 1000 * a + 100 * b + 10 *c + d = 999 * a + 99 * b + 9 *c + a + b + c + d, just take the remainder of 9 directly

class Solution {
    
    
public:
    int addDigits(int num) {
    
    
        while (num > 9)
        {
    
    
            int ret = 0;
            while (num > 0)
            {
    
    
                ret += num % 10;
                num = num / 10;
            }
            num = ret;
        }

        return num;

    }
};
class Solution {
    
    
public:
    int addDigits(int num) {
    
    
        while (num > 9)
        {
    
    
            num = (num - 1) % 9 + 1;
        }
        return num;
    }
};
  1. Numbers that appear only once.
    Given an integer array nums, exactly two elements appear only once, and all other elements appear twice. Find the two elements that appear only once.

This problem can be solved by sorting and hash table, but the optimal solution is bit operation. The core idea here is that the same elements can be removed through XOR. Through the AND operation of the complement code and the original code, we can get the lowest difference between the two elements, which is the principle of judgment.

class Solution {
    
    
public:
vector<int> singleNumber(vector<int>& nums) 
{
    
    
    int sign = 0;
    //取得数组中两个唯一数的按位异或结果
    for (int i = 0; i < nums.size(); i++)
    {
    
    
        sign ^= nums[i];
    }
    //获取区分两个唯一数的比特位所代表的值
    //也可以写成:sign &= (~sign) + 1
    sign &= -sign;
    int n1 = 0, n2 = 0;
    //通过标识,区分两个数组
    for (int i = 0; i < nums.size(); i++)
    {
    
    
        if ((nums[i] & sign) == sign)
            n1 ^= nums[i];
        else
            n2 ^= nums[i]; ;
    }
    return {
    
     n1,n2 };
}
};
  1. Itinerary and users
    Write a SQL statement to find out the cancellation rate of non-banned users from October 1, 2013 to October 3, 2013.

Connect the trips table and users table. The connection condition is that the passengers corresponding to the itinerary are not forbidden and the drivers are not forbidden. The
order date is filtered between the target dates. The date is
used to group
and count all the orders and the number of cancelled orders. The number of cancelled orders is used A bool condition is used to get 0 or 1, and then use avg to average.
Keep two decimal places for the order cancellation rate, and rename the output column name

# Write your MySQL query statement below
SELECT
    request_at as 'Day', round(avg(Status!='completed'), 2) as 'Cancellation Rate'
FROM 
    trips t JOIN users u1 ON (t.client_id = u1.users_id AND u1.banned = 'No')
    JOIN users u2 ON (t.driver_id = u2.users_id AND u2.banned = 'No')
WHERE	
    request_at BETWEEN '2013-10-01' AND '2013-10-03'
GROUP BY 
    request_at


  1. Ugly numbers
    Write a program to determine whether the given number is an ugly number.
    Ugly numbers are positive integers containing only prime factors 2, 3, and 5.

Just divide by loop

class Solution {
public:
    bool isUgly(int num) {

        if (num == 0) return false;
        
        set<int> ugly = {
   
   2, 3, 5};

        for (auto div : ugly)
        {
            while (num % div == 0)
            {
                num = num / div;               
            }
        }

        if (num == 1) 
            return true;
        else
            return false;
    }
};
  1. Ugly number 2
    Write a program to find the nth ugly number.
    Ugly numbers are positive integers whose prime factors only contain 2, 3, and 5.

This problem is solved by dynamic programming, which requires three pointers to point to the last multiplied number, and then take the smallest number of the three numbers each time, and then move the pointer. Note that the dynamic programming of this question is not suitable for dimensionality reduction: because there are many dependencies

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> dp(n, 0);
        dp[0] = 1;
        int p2 = 0, p3 = 0, p5 = 0;
        for(int i = 1; i < n; i ++){
            dp[i] = min(min(dp[p2] * 2, dp[p3] * 3), dp[p5] * 5);
            if(dp[i] == dp[p2]*2) p2++;
            if(dp[i] == dp[p3]*3) p3++;
            if(dp[i] == dp[p5]*5) p5++;
        }
        return dp[n - 1];
    }
};

Guess you like

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