Leetcode problem-solving ideas analysis (twenty-four) 168-177

  1. Excel table name
    Given a positive integer, return its corresponding column name in the Excel table.

Base conversion

class Solution {
    
    
public:
    string convertToTitle(int n) 
    {
    
    
        string ans = "";
        while (n > 0)
        {
    
    
            n -= 1;
            ans.push_back('A' + (n % 26));
            n /= 26;
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};


  1. Majority elements
    Given an array of size n, find the majority of elements in it. Most elements refer to elements that appear more than ⌊ n/2 ⌋ in the array.
    You can assume that the array is non-empty, and there will always be a majority of elements in a given array.

It's easy to solve with hash table

class Solution {
    
    
public:
    int majorityElement(vector<int>& nums) 
    {
    
    
        unordered_map<int, int> map;
        for (int i = 0; i < nums.size(); i++)
        {
    
    
            map[nums[i]]++;
            if (map[nums[i]] > nums.size() / 2)
            {
    
    
                return nums[i];
            }
        }
        return -1;
    }
};

After sorting, the middle must be the majority

class Solution {
    
    
public:
    int majorityElement(vector<int>& nums) {
    
    
        sort(nums.begin(), nums.end());
        return nums[nums.size() / 2];
    }
};

Another way of thinking is to set other numbers to -1 and the mode to 1, then the sum must be greater than 0. So we can maintain a candidate mode candidate and its occurrence count. Initially candidate can be any value, count is 0;
we traverse all the elements in the array nums, for each element x, before judging x, if the value of count is 0, we first assign the value of x to candidate, and then we Judge x:
If x is equal to candidate, then the value of counter count is increased by 1;
if x is not equal to candidate, then the value of counter count is decreased by 1.
After the traversal is complete, the candidate is the mode of the entire array.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = -1;
        int count = 0;
        for (int num : nums) {
            if (num == candidate)
                ++count;
            else if (--count < 0) {
                candidate = num;
                count = 1;
            }
        }
        return candidate;
    }
};

  1. Excel table column serial number
    Given a column name in an Excel table, return its corresponding column serial number.

Too simple to say

class Solution {
    
    
public:
    int titleToNumber(string s) {
    
    
        int ret = 0;
        for (auto c : s)
        {
    
    
            ret = ret * 26 + (c - 'A' + 1);
        }
        return ret;
    }
};
  1. Zero after factorial
    Given an integer n, return n! The number of zeros in the mantissa of the result.
    The number of 0 in the factorial depends on the number of 5 and 2. Because there are so many 2s, you can actually just look at the number of 5.
class Solution {
    
    
public:
    int trailingZeroes(int n) {
    
    
        int five = 0;
        while(n >= 5){
    
    
            five += n/5;
            n/=5;
        }
        return five;
    }
};
  1. Binary Tree Search Iterator
    Implement a binary search tree iterator. You will initialize the iterator with the root node of the binary search tree.
    Calling next() will return the next smallest number in the binary search tree.

This question is actually a variant of in-order traversal. It takes a stack to save the current position, and then continues to find the next leftmost node after popping the stack.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
    
    
    stack<TreeNode *> m_stack;
public:
    BSTIterator(TreeNode* root) {
    
    
        while (root)
        {
    
    
            m_stack.push(root);
            root = root->left;
        }
    }
    
    /** @return the next smallest number */
    int next() {
    
    
        int ret = m_stack.top()->val;
        TreeNode *tmp = m_stack.top()->right;
        m_stack.pop();        
        while (tmp)
        {
    
    
            m_stack.push(tmp);
            tmp = tmp->left;
        }
        return ret;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
    
    
        return !m_stack.empty();
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */
  1. Dungeon game

This question is similar to the previous grid, which is solved by dynamic programming. The difference is that this question needs to consider that the blood volume cannot be lower than 0, so from the end to the starting point is the correct solution.

class Solution {
    
    
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
    
    
        //  m 为行数,n 为列数
        int m = dungeon.size();
        int n = dungeon[0].size();
        
        //  初始化一个数组用于更新需要被扣掉生命值(以下简称生命值)
        vector<int> line(n, INT32_MIN);
        line[n - 1] = 0;
        
        //  从最后一行的最右边开始更新生命值
        for (int i = m - 1; i >= 0; i--) {
    
    
            line[n - 1] += dungeon[i][n - 1];
            line[n - 1] = (line[n - 1] > 0) ? 0 : line[n - 1];

            for (int j = n - 2; j >= 0; j--) {
    
    
                line[j] = max(line[j], line[j + 1]) + dungeon[i][j];
                line[j] = (line[j] > 0) ? 0 : line[j];
            }
        }
        return 1 - line[0];
    }
};


  1. Combine the two tables and
    write a SQL query that meets the condition: regardless of whether the person has address information, you need to provide person information based on the above two tables

The point of investigation is the joint query of multiple tables. The main memory is
1) left join, the join result retains all the data of the left table
2) right join, the join result retains all the data of the right table
3) inner join (Inner join), take the common data of the two tables.

# Write your MySQL query statement below
select FirstName, LastName, City, State
from Person left join Address
on Person.PersonId = Address.PersonId;
  1. The second highest salary
    Write a SQL query to get the second highest salary (Salary) in the Employee table.

Sort first and then query, use IFNULL to avoid the second highest being NULL

# Write your MySQL query statement below
SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary


  1. The Nth highest salary
    custom variable realizes the ranking of data in descending order of salary, and the same salary and the same name do not skip grades, that is, after 3000, 2000, 2000, and 1000 are ranked 1, 2, 2, and 3;
    for temporary tables with ranking information Second screening, get the
    salary ranked N ; because there may be more than one record with salary rank N, use distinct to remove the duplicate
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      # Write your MySQL query statement below.
      SELECT 
          DISTINCT salary 
      FROM 
          (SELECT 
                salary, @r:=IF(@p=salary, @r, @r+1) AS rnk,  @p:= salary 
            FROM  
                employee, (SELECT @r:=0, @p:=NULL)init 
            ORDER BY 
                salary DESC) tmp
      WHERE rnk = N
  );
END


Guess you like

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