楼主: Myron2017
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题记录帖子

🔗
 楼主| Myron2017 2026-3-19 10:41:00 来自APP | 只看该作者
全局:
3726. Remove Zeros in Decimal Representation
Solved
Easy
Topics
Hint
You are given a positive integer n.

Return the integer obtained by removing all zeros from the decimal representation of n.



Example 1:

Input: n = 1020030

Output: 123

Explanation:

After removing all zeros from 1020030, we get 123.

Example 2:

Input: n = 1

Output: 1

Explanation:

1 has no zero in its decimal representation. Therefore, the answer is 1.



Constraints:

1 <= n <= 1015
  1. class Solution:
  2.     def removeZeros(self, n: int) -> int:
  3.         ans = [ch for ch in str(n)  if ch != '0']
  4.         return int("".join(ans))
  5.         
复制代码

补充内容 (2026-03-19 10:42 +08:00):
面试小技巧:在 Python 中,其实还有一个更直接的写法:
  1. str(n).replace('0', '')
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-19 10:47:21 | 只看该作者
全局:
3718. Smallest Missing Multiple of K
Solved
Easy
Topics
Hint
Given an integer array nums and an integer k, return the smallest positive multiple of k that is missing from nums.

A multiple of k is any positive integer divisible by k.



Example 1:

Input: nums = [8,2,3,4,6], k = 2

Output: 10

Explanation:

The multiples of k = 2 are 2, 4, 6, 8, 10, 12... and the smallest multiple missing from nums is 10.

Example 2:

Input: nums = [1,4,7,10,15], k = 5

Output: 5

Explanation:

The multiples of k = 5 are 5, 10, 15, 20... and the smallest multiple missing from nums is 5.



Constraints:

1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= k <= 100
  1. class Solution:
  2.     def missingMultiple(self, nums: List[int], k: int) -> int:
  3.         s = set(nums)
  4.         multiple = 1

  5.         while True:
  6.             if multiple * k not in s:
  7.                 return multiple * k
  8.             multiple += 1
  9.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-19 10:52:04 | 只看该作者
全局:
LC. 2891. Method Chaining

Pandas 的 Chaining of methods
  1. import pandas as pd

  2. def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
  3.     return animals[ animals['weight'] > 100 ].sort_values(by='weight', ascending=False)[['name']]
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-19 11:16:26 | 只看该作者
全局:
LC. 2621. Sleep

核心概念速记
🔑 三大主角

Promise — 异步操作的"承诺",最终会 resolve(成功)或 reject(失败)
setTimeout — 延迟执行代码,不阻塞主线程
async/await — 让异步代码写起来像同步代码的语法糖


⚙️ 事件循环机制
代码执行 → 遇到异步操作 → 挂起,继续执行后面的代码
               ↓
         异步完成后,回调进入任务队列
               ↓
         调用栈为空时,事件循环取出队列中的任务执行

⚠️ setTimeout 的延迟是最短等待时间,不是精确时间


💤 sleep 函数实现(本题核心)
javascriptasync function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}
原理:创建一个 Promise,在 millis 毫秒后调用 resolve,完成"暂停"效果。

📝 Promise 三种写法对比
写法特点.then().catch().finally()链式调用,层级多时较繁琐async/await + try/catch线性结构,更易读 ✅直接返回 Promise最简洁,适合简单场景

⏱️ 复杂度

时间 O(1),空间 O(1)(与输入值无关,只涉及创建 Promise 和定时器)
  1. /**
  2. * [url=home.php?mod=space&uid=1215059]@param[/url] {number} millis
  3. * [url=home.php?mod=space&uid=160137]@return[/url] {Promise}
  4. */
  5. async function sleep(millis) {
  6.     await new Promise(res => setTimeout(res, millis));
  7. }

  8. /**
  9. * let t = Date.now()
  10. * sleep(100).then(() => console.log(Date.now() - t)) // 100
  11. */
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-21 10:44:22 | 只看该作者
全局:
LC. 3643. Flip Square Submatrix Vertically
  1. class Solution:
  2.     def reverseSubmatrix(self, grid: List[List[int]], x: int, y: int, k: int) -> List[List[int]]:
  3.         row1 = x
  4.         row2 = x + k - 1

  5.         while row2 > row1:
  6.             # switch
  7.             for i in range(k):
  8.                 tmp = grid[row1][y+i]
  9.                 grid[row1][y+i] = grid[row2][y+i]
  10.                 grid[row2][y+i] = tmp
  11.             # update row2, row 1
  12.             row2 -= 1
  13.             row1 += 1
  14.         
  15.         return grid
  16.         
复制代码
利用 Python 切片
  1. from typing import List

  2. class Solution:
  3.     def reverseSubmatrix(self, grid: List[List[int]], x: int, y: int, k: int) -> List[List[int]]:
  4.         # 1. 确定子矩阵的上下边界
  5.         top, bottom = x, x + k - 1
  6.         
  7.         # 2. 双指针向中间收缩
  8.         while top < bottom:
  9.             # 3. 交换 top 行和 bottom 行中,从 y 到 y+k 的那一部分
  10.             # 使用切片赋值,既简洁又高效
  11.             grid[top][y : y+k], grid[bottom][y : y+k] = \
  12.                 grid[bottom][y : y+k], grid[top][y : y+k]
  13.             
  14.             top += 1
  15.             bottom -= 1
  16.             
  17.         return grid
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-22 11:19:15 | 只看该作者
全局:
LC. 243. Shortest Word Distance
  1. class Solution:
  2.     def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
  3.         index_dict = defaultdict(list)
  4.         for i, w in enumerate(wordsDict):
  5.             if w == word1:
  6.                 index_dict[word1].append(i)
  7.             if w == word2:
  8.                 index_dict[word2].append(i)
  9.         
  10.         ans = float('inf')

  11.         for i in index_dict[word1]:
  12.             for j in index_dict[word2]:
  13.                 ans = min(ans, abs(j - i) )
  14.         return ans
复制代码
我的解法并不是最好的,还是要学习啊。

其实写的时候我就发现了,存下所有的 index 并不是最优的,因为显然我不需要隔着一个 w1 去算同一个 w2 的距离,中间隔着的那个 w1 一定更近。

但是还是没想到最好的思路,所以直接暴力了。

其实思路就是维持两个指针,p1, p2 来 track word1, word2,只要p1 or p2 更新就计算下和当前的对方的单词的距离,因为这样就只是计算相邻 pair 的距离。
  1. class Solution:
  2.     def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
  3.         p1, p2 = -1, -1
  4.         min_dist = len(wordsDict)
  5.         
  6.         for i, word in enumerate(wordsDict):
  7.             if word == word1:
  8.                 p1 = i
  9.                 # 只有 p1 更新了,且 p2 已经存在时才计算
  10.                 if p2 != -1:
  11.                     min_dist = min(min_dist, p1 - p2)
  12.             elif word == word2:
  13.                 p2 = i
  14.                 # 只有 p2 更新了,且 p1 已经存在时才计算
  15.                 if p1 != -1:
  16.                     min_dist = min(min_dist, p2 - p1)
  17.                     
  18.             # 💡 炫技小提示:如果 min_dist 已经减小到 1,可以直接返回了
  19.             # 因为 1 是两个不同单词能达到的最小距离
  20.             if min_dist == 1:
  21.                 return 1
  22.                
  23.         return min_dist
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-23 03:19:48 | 只看该作者
全局:
LC. 257. Binary Tree Paths

二叉树还是有一点问题,pop 的时候忘记正确的位置了。虽然过了,但是还是不行说实话。
  1. class Solution:
  2.     def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
  3.         ans = []
  4.         if not root: return []

  5.         def DFS(path, node):
  6.             # 1. 进场:先把当前节点加入路径
  7.             path.append(str(node.val))
  8.             
  9.             # 2. 判断:是否是叶子
  10.             if not node.left and not node.right:
  11.                 ans.append("->".join(path))
  12.                 # 注意:这里不能直接 return,因为末尾还要统一 pop
  13.             else:
  14.                 # 3. 递归:去左右子树找
  15.                 if node.left:
  16.                     DFS(path, node.left)
  17.                 if node.right:
  18.                     DFS(path, node.right)
  19.             
  20.             # 4. 出场:回溯!把当前节点弹出,保证 path 干净地回到父节点手中
  21.             path.pop()

  22.         DFS([], root)
  23.         return ans
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-23 03:46:36 来自APP | 只看该作者
全局:
LC  185. Department Top Three Salaries
Solved
Hard
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Employee

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| id           | int     |
| name         | varchar |
| salary       | int     |
| departmentId | int     |
+--------------+---------+
id is the primary key (column with unique values) for this table.
departmentId is a foreign key (reference column) of the ID from the Department table.
Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.


Table: Department

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the ID of a department and its name.


A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department.

Write a solution to find the employees who are high earners in each of the departments.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Employee table:
+----+-------+--------+--------------+
| id | name  | salary | departmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
+----+-------+--------+--------------+
Department table:
+----+-------+
| id | name  |
+----+-------+
| 1  | IT    |
| 2  | Sales |
+----+-------+
Output:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Joe      | 85000  |
| IT         | Randy    | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+
Explanation:
In the IT department:
- Max earns the highest unique salary
- Both Randy and Joe earn the second-highest unique salary
- Will earns the third-highest unique salary

In the Sales department:
- Henry earns the highest salary
- Sam earns the second-highest salary
- There is no third-highest salary as there are only two employees


Constraints:

There are no employees with the exact same name, salary and department.
  1. SELECT
  2.     d.name AS Department,
  3.     e.name AS Employee,
  4.     e.salary AS Salary
  5. FROM (
  6.     SELECT
  7.         departmentId,
  8.         name,
  9.         salary,
  10.         DENSE_RANK() OVER (
  11.             PARTITION BY departmentId
  12.             ORDER BY salary DESC
  13.         ) AS rnk
  14.     FROM Employee
  15. ) e
  16. JOIN Department d ON e.departmentId = d.id
  17. WHERE e.rnk <= 3;
复制代码




补充内容 (2026-03-23 03:48 +08:00):


补充内容 (2026-03-23 03:49 +08:00):
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-23 03:52:16 | 只看该作者
全局:
LC 184. Department Highest Salary
Solved
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Employee

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| id           | int     |
| name         | varchar |
| salary       | int     |
| departmentId | int     |
+--------------+---------+
id is the primary key (column with unique values) for this table.
departmentId is a foreign key (reference columns) of the ID from the Department table.
Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.


Table: Department

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table. It is guaranteed that department name is not NULL.
Each row of this table indicates the ID of a department and its name.


Write a solution to find employees who have the highest salary in each of the departments.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Employee table:
+----+-------+--------+--------------+
| id | name  | salary | departmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Jim   | 90000  | 1            |
| 3  | Henry | 80000  | 2            |
| 4  | Sam   | 60000  | 2            |
| 5  | Max   | 90000  | 1            |
+----+-------+--------+--------------+
Department table:
+----+-------+
| id | name  |
+----+-------+
| 1  | IT    |
| 2  | Sales |
+----+-------+
Output:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Jim      | 90000  |
| Sales      | Henry    | 80000  |
| IT         | Max      | 90000  |
+------------+----------+--------+
Explanation: Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.

同样用上一贴的SQL代码,只需要修改最后的筛选条件。
  1. # Write your MySQL query statement below
  2. SELECT
  3.     d.name AS Department,
  4.     e.name AS Employee,
  5.     e.salary AS Salary
  6. FROM (
  7.     SELECT
  8.         departmentId,
  9.         name,
  10.         salary,
  11.         DENSE_RANK() OVER (
  12.             PARTITION BY departmentId
  13.             ORDER BY salary DESC
  14.         ) AS rnk
  15.     FROM Employee
  16. ) e
  17. JOIN Department d ON e.departmentId = d.id
  18. WHERE e.rnk <= 1;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-3-24 10:42:03 | 只看该作者
全局:
LC  238. Product of Array Except Self

既然不能用除法,就把“除了自己以外的乘积”拆解为“左边的乘积 x 右边的乘积”
  1. class Solution:
  2.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  3.         n = len(nums)
  4.         ans = [1] * n

  5.         # 1. 计算前缀积:ans[i] 表示 i 左侧所有元素的乘积
  6.         # 我们可以直接从 0 开始,逻辑更统一
  7.         pre = 1
  8.         for i in range(n):
  9.             ans[i] = pre
  10.             pre *= nums[i]

  11.         # 2. 计算后缀积并直接乘入 ans
  12.         # suf 表示 i 右侧所有元素的乘积
  13.         suf = 1
  14.         for i in range(n - 1, -1, -1):
  15.             ans[i] *= suf
  16.             suf *= nums[i]

  17.         return ans
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表