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

刷题记录帖子

🔗
 楼主| Myron2017 2026-2-17 11:47:14 | 只看该作者
全局:
LC 401. Binary Watch

题目希望的做法,用 bit—count
  1. class Solution:
  2.     def readBinaryWatch(self, turnedOn: int):
  3.         res = []
  4.         
  5.         for h in range(12):
  6.             for m in range(60):
  7.                 if (h.bit_count() + m.bit_count()) == turnedOn:
  8.                     res.append(f"{h}:{m:02d}")
  9.         
  10.         return res
复制代码
但是我觉得更好的程序员的想法应该是,DFS
  1. from typing import List

  2. class Solution:
  3.     def readBinaryWatch(self, turnedOn: int) -> List[str]:
  4.         if turnedOn > 8:   # 最多 8 个灯还能合法
  5.             return []

  6.         hours = [8, 4, 2, 1]
  7.         minutes = [32, 16, 8, 4, 2, 1]
  8.         
  9.         res = []

  10.         # 生成所有和为 val 且使用 k 个灯的组合
  11.         def dfs(arr, start, k, cur_sum, result, limit):
  12.             if k == 0:
  13.                 if cur_sum <= limit:
  14.                     result.append(cur_sum)
  15.                 return
  16.             
  17.             for i in range(start, len(arr)):
  18.                 dfs(arr, i + 1, k - 1, cur_sum + arr[i], result, limit)

  19.         # 枚举小时用几个灯
  20.         for h_used in range(0, min(4, turnedOn) + 1):
  21.             m_used = turnedOn - h_used
  22.             if m_used > 6:
  23.                 continue
  24.             
  25.             hour_vals = []
  26.             minute_vals = []

  27.             dfs(hours, 0, h_used, 0, hour_vals, 11)
  28.             dfs(minutes, 0, m_used, 0, minute_vals, 59)

  29.             for h in hour_vals:
  30.                 for m in minute_vals:
  31.                     res.append(f"{h}:{m:02d}")

  32.         return res
复制代码
这道题目完全可以作为 DFS 的练手题目。
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-19 12:01:55 | 只看该作者
全局:
LC 696. Count Binary Substrings

发现子串必须是 000111 或 111000 结构

本质是相邻连续段匹配

每一对相邻段贡献 min(长度1, 长度2)
  1. class Solution:
  2.     def countBinarySubstrings(self, s: str) -> int:
  3.         # prev 表示前一段连续字符的长度
  4.         prev = 0
  5.         
  6.         # curr 表示当前这段连续字符的长度
  7.         # 初始化为 1,因为第一个字符已经构成一个长度为 1 的连续段
  8.         curr = 1
  9.         
  10.         # 用来统计符合条件的子串数量
  11.         ans = 0

  12.         # 从第二个字符开始遍历
  13.         for i in range(1, len(s)):
  14.             
  15.             # 如果当前字符和前一个字符相同
  16.             # 说明还在同一个连续段内
  17.             if s[i] == s[i-1]:
  18.                 curr += 1
  19.             
  20.             else:
  21.                 # 出现字符变化,说明当前连续段结束
  22.                
  23.                 # 相邻两段可以构成的合法子串数量为
  24.                 # min(前一段长度, 当前段长度)
  25.                 ans += min(prev, curr)
  26.                
  27.                 # 当前段变成下一次的前一段
  28.                 prev = curr
  29.                
  30.                 # 重置当前段长度为 1(当前字符是新一段的开始)
  31.                 curr = 1

  32.         # 循环结束后,最后一段还没有计算
  33.         # 需要再计算一次
  34.         ans += min(prev, curr)

  35.         return ans
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-21 10:44:55 | 只看该作者
全局:
LC 762. Prime Number of Set Bits in Binary Representation

数量级比较小,直接暴力统计 1 in binary number 的个数统计下就行。
  1. class Solution:
  2.     def countPrimeSetBits(self, left: int, right: int) -> int:
  3.         # 2^20 > 10^6 > 2^19
  4.         # so the total length of left, right in binary musht < 20
  5.         #  < 20, we have 2, 3, 5, 7, 11, 13, 17, 19 prime numbers
  6.         ans = 0
  7.         primes = (2, 3, 5, 7, 11, 13, 17, 19)

  8.         def count_bit(n):
  9.             count = 0
  10.             while n:
  11.                 n = n & (n-1)
  12.                 count += 1
  13.             return count

  14.         for i in range(left, right+1):
  15.             #if i.bit_count() in primes: ans += 1
  16.             if count_bit(i) in primes: ans += 1
  17.         return ans
复制代码
当然复杂了的话,就是区间 DP 了。

一、问题转化

我们要计算:

[left, right] 区间中
bit_count(x) 是质数 的个数

经典套路:

f(right) - f(left - 1)

所以核心变成:

计算 0 ~ n 中,bit_count 是质数的个数

二、数位 DP 思路

我们按二进制位,从高位到低位枚举。

定义状态:

dp(pos, count_ones, is_limit)

含义:

pos:当前处理到第几位

count_ones:当前已经用了多少个 1

is_limit:当前是否受上界限制

三、为什么这样设计?

因为我们是逐位构造数字。

例如:

n = 13 = 1101 (二进制)

我们逐位决定:

这一位放 0 还是 1

不能超过上界

四、完整代码(真正数位 DP)
  1. class Solution:
  2.     def countPrimeSetBits(self, left: int, right: int) -> int:
  3.         
  4.         primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}
  5.         
  6.         # 计算 0 ~ n 的答案
  7.         def count(n: int) -> int:
  8.             if n < 0:
  9.                 return 0
  10.             
  11.             bits = list(map(int, bin(n)[2:]))  # 二进制位列表
  12.             length = len(bits)
  13.             
  14.             from functools import lru_cache
  15.             
  16.             @lru_cache(None)
  17.             def dp(pos: int, count_ones: int, is_limit: bool) -> int:
  18.                
  19.                 # 所有位处理完
  20.                 if pos == length:
  21.                     return 1 if count_ones in primes else 0
  22.                
  23.                 total = 0
  24.                
  25.                 # 当前位最多能填多少
  26.                 upper = bits[pos] if is_limit else 1
  27.                
  28.                 for digit in range(upper + 1):
  29.                     total += dp(
  30.                         pos + 1,
  31.                         count_ones + digit,
  32.                         is_limit and digit == upper
  33.                     )
  34.                
  35.                 return total
  36.             
  37.             return dp(0, 0, True)
  38.         
  39.         return count(right) - count(left - 1)
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-21 11:06:22 | 只看该作者
全局:
LC 183. Customers Who Never Order

183. Customers Who Never Order
Solved
Easy
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Customers

+-------------+---------+
| 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 and name of a customer.


Table: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| customerId  | int  |
+-------------+------+
id is the primary key (column with unique values) for this table.
customerId is a foreign key (reference columns) of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.


Write a solution to find all customers who never order anything.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Customers table:
+----+-------+
| id | name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
Output:
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+
  1. SELECT c.name AS Customers
  2. FROM Customers c
  3. LEFT JOIN Orders o
  4.     ON c.id = o.customerId
  5. WHERE o.id IS NULL;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-21 11:10:39 来自APP | 只看该作者
全局:
181. Employees Earning More Than Their Managers
Easy
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Employee

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| salary      | int     |
| managerId   | int     |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.


Write a solution to find the employees who earn more than their managers.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Employee table:
+----+-------+--------+-----------+
| id | name  | salary | managerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | Null      |
| 4  | Max   | 90000  | Null      |
+----+-------+--------+-----------+
Output:
+----------+
| Employee |
+----------+
| Joe      |
+----------+
Explanation: Joe is the only employee who earns more than his manager.

自连接(Self Join)


解释

JOIN Employee m ON e.managerId = m.id

这里把 Employee 表自己和自己连起来

e 是普通员工,m 是经理

e.managerId 对应 m.id

WHERE e.salary > m.salary

筛选出工资高于经理的员工

SELECT e.name AS Employee

返回员工姓名
  1. SELECT e.name AS Employee
  2. FROM Employee e
  3. JOIN Employee m
  4.     ON e.managerId = m.id
  5. WHERE e.salary > m.salary;
复制代码

补充内容 (2026-02-21 11:11 +08:00):
注意点
  • 如果
    1. managerId IS NULL
    复制代码
    的员工(顶级经理)
    • JOIN 后不会匹配到 m.id
    • 自然不会出现在结果里 ✅
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-21 12:00:46 | 只看该作者
全局:
178. Rank Scores
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Scores

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| score       | decimal |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains the score of a game. Score is a floating point value with two decimal places.


Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:

The scores should be ranked from the highest to the lowest.
If there is a tie between two scores, both should have the same ranking.
After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.
Return the result table ordered by score in descending order.

The result format is in the following example.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     score,
  4.     DENSE_RANK() OVER (ORDER BY score DESC) AS 'rank'
  5. FROM Scores
  6. ORDER BY score DESC;
复制代码
DENSE_RANK() OVER (ORDER BY score DESC)

按分数从高到低排序

相同分数得到相同排名

下一个不同分数的排名紧跟前面的排名(不跳号)

ORDER BY score DESC

最终输出按分数从高到低排列

如果你用 RANK():

会出现跳号:

score: 90.50 90.50 88.00 85.00
rank:  1      1      3      4
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-22 12:25:29 | 只看该作者
全局:
LC 868. Binary Gap
  1. class Solution:
  2.     def binaryGap(self, n: int) -> int:
  3.         ans = -1
  4.         prev_one_index = -1
  5.         bin_n = str(bin(n)[2:])

  6.         for i in range(len(bin_n)):
  7.             if bin_n[i] == '1':
  8.                 if prev_one_index == -1:
  9.                     prev_one_index = i
  10.                 else:
  11.                     ans = max(ans, i - prev_one_index)
  12.                     prev_one_index = i
  13.         if ans != -1: return ans
  14.         else: return 0
复制代码
更好的 code,先处理 happy case
  1. class Solution:
  2.     def binaryGap(self, n: int) -> int:
  3.         s = bin(n)[2:]  # 转为二进制字符串,去掉 '0b' 前缀
  4.         max_dist = 0
  5.         last_pos = -1
  6.         
  7.         for i, char in enumerate(s):
  8.             if char == '1':
  9.                 if last_pos != -1:
  10.                     max_dist = max(max_dist, i - last_pos)
  11.                 last_pos = i
  12.                
  13.         return max_dist
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-23 09:50:02 | 只看该作者
全局:
LC. 1461. Check If a String Contains All Binary Codes of Size K
  1. class Solution:
  2.     def hasAllCodes(self, s: str, k: int) -> bool:
  3.         # get all substring with length k
  4.         sub_str_set = set()
  5.         for i in range(0, len(s) - k + 1):
  6.             sub_str_set.add(s[i:i+k])
  7.         
  8.         return len(sub_str_set) == 2**k
  9.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-23 10:18:59 | 只看该作者
全局:
319. Bulb Switcher

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.

On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.

Return the number of bulbs that are on after n rounds.



Example 1:


Input: n = 3
Output: 1
Explanation: At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.
Example 2:

Input: n = 0
Output: 0
Example 3:

Input: n = 1
Output: 1


Constraints:

0 <= n <= 109

其实我不喜欢这道题目,我也不觉得这是一道好的面试题目,因为你在考察面试者是不是知道这个数学知识点。
我觉得想到 反过来说,第 $k$ 个灯泡会在所有是 $k$ 的约数的轮次被切换。
但是对于某个数来说,
普通数字(非完全平方数):约数总是成双成对出现的。例如 $n = 12$:$1 \times 12 = 12$$2 \times 6 = 12$$3 \times 4 = 12$约数集合:$\{1, 2, 3, 4, 6, 12\}$,共 6 个(偶数)。完全平方数:约数依然成对出现,但其中有一对是重复的。例如 $n = 16$:$1 \times 16 = 16$$2 \times 8 = 16$$4 \times 4 = 16$  $\leftarrow$ 重点在这里!约数集合:$\{1, 2, 4, 8, 16\}$,共 5 个(奇数)。数字 $4$ 独自成对,导致总数变成了奇数。

这里需要注意,虽然约数个数是偶数,但是因为 1 不参与打开灯的操作,所以偶数个约数的灯最后是关闭的,因为实际是奇数次开关。
奇数个约数的灯,因为排除了 1 ,所以最后是打开的。

所以题目代码很简单。

  1. class Solution:
  2.     def bulbSwitch(self, n: int) -> int:
  3.         if n == 0: return 0
  4.         if n == 1: return 1

  5.         return int(n**0.5)
  6.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-2-23 10:26:51 | 只看该作者
全局:
877. Stone Game
Solved
Medium
Topics
conpanies icon
Companies
Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.

Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.

Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.



Example 1:

Input: piles = [5,3,4,5]
Output: true
Explanation:
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes [3, 4, 5].
If Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
Example 2:

Input: piles = [3,7,2,3]
Output: true


Constraints:

2 <= piles.length <= 500
piles.length is even.
1 <= piles[i] <= 500
sum(piles[i]) is odd.

如果你尝试用动态规划 (DP) 去解,你会写出 $O(n^2)$ 的代码并顺利通过;但如果你看穿了这道题的本质,你会发现它的答案永远是 return True。这又是数学思维对暴力模拟的一次“降维打击”。1. 核心前提(三个关键点)题目给出了三个至关重要的限制条件:石子堆的总数是偶数(piles.length is even)。石子的总数是奇数(sum(piles) is odd),这意味着不可能平局。Alice 先手。2. Alice 的“必胜策略”:奇偶位选择权因为总堆数是偶数,我们可以把这些堆按索引分为奇数位和偶数位。假设 piles = [5, 3, 4, 5]:偶数位(索引 0, 2):5, 4,总和为 $9$。奇数位(索引 1, 3):3, 5,总和为 $8$。Alice 作为先手,可以控制自己拿走所有的偶数位,或者所有的奇数位!她是怎么做到的?想拿全部偶数位:Alice 先拿 piles[0](偶数位)。剩下的数组两端就变成了索引 1 和索引 $n-1$(都是奇数位)。无论 Bob 拿哪一头,他都只能拿走一个奇数位。Bob 拿完后,数组的两端又会露出一堆偶数位供 Alice 选择。想拿全部奇数位:Alice 先拿 piles[n-1](最后一个,索引是奇数)。同理,她可以迫使 Bob 只能接触偶数位,而自己把奇数位全卷走。3. 为什么 Alice 必胜?既然 Alice 可以计算出“奇数位总和”与“偶数位总和”哪个更大,而总数又是奇数(保证了两者一定不相等),那么:如果 偶数位总和 > 奇数位总和,Alice 就全程只拿偶数位。如果 奇数位总和 > 偶数位总和,Alice 就全程只拿奇数位。结论: 只要 Alice 足够聪明(Optimal Play),她从第一步开始就已经锁定了胜局。
回复

使用道具 举报

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

本版积分规则

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