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

刷题记录帖子

🔗
 楼主| Myron2017 2026-4-8 10:30:24 | 只看该作者
全局:
LC. 3653. XOR After Range Multiplication Queries I

数据量小,直接暴力解决。

当然我犯了个错,用了 OR 而不是 XOR; 也忘记了 XOR 的性质。
  1. # 你的代码:
  2. for i in range(1, len(nums)):
  3.     ans = ans | nums[i]  # ❌ 这里的 '|' 是按位或 (OR)

  4. # 正确写法:
  5. for i in range(1, len(nums)):
  6.     ans = ans ^ nums[i]  # ✅ 这里的 '^' 是按位异或 (XOR)
复制代码
异或的初始值技巧:根据异或的性质 0 ^ X = X,我们可以直接把初始值设为 0,然后遍历整个数组,这样就不需要把 nums[0] 单独拎出来,代码更整洁。
  1. class Solution:
  2.     def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int:
  3.         mod = 10**9 + 7
  4.         for q in queries:
  5.             l, r, k, v = q
  6.             for i in range(l, r+1, k):
  7.                 nums[i] = (nums[i] * v) % mod
  8.         
  9.         ans = 0

  10.         for num in nums:
  11.             ans = ans ^ num

  12.         return ans  
复制代码
当然这题,如果数据量扩大,就是 Hard 了,3655. XOR After Range Multiplication Queries II
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-9 08:35:28 | 只看该作者
全局:
LC 3687. Library Late Fee Calculator

You are given an integer array daysLate where daysLate[i] indicates how many days late the ith book was returned.

The penalty is calculated as follows:

If daysLate[i] == 1, penalty is 1.
If 2 <= daysLate[i] <= 5, penalty is 2 * daysLate[i].
If daysLate[i] > 5, penalty is 3 * daysLate[i].
Return the total penalty for all books.



Example 1:

Input: daysLate = [5,1,7]

Output: 32

Explanation:

daysLate[0] = 5: Penalty is 2 * daysLate[0] = 2 * 5 = 10.
daysLate[1] = 1: Penalty is 1.
daysLate[2] = 7: Penalty is 3 * daysLate[2] = 3 * 7 = 21.
Thus, the total penalty is 10 + 1 + 21 = 32.
Example 2:

Input: daysLate = [1,1]

Output: 2

Explanation:

daysLate[0] = 1: Penalty is 1.
daysLate[1] = 1: Penalty is 1.
Thus, the total penalty is 1 + 1 = 2.


Constraints:

1 <= daysLate.length <= 100
1 <= daysLate[i] <= 100
  1. class Solution:
  2.     def lateFee(self, daysLate: List[int]) -> int:
  3.         total = 0

  4.         for dl in daysLate:

  5.             if dl == 1: total += 1
  6.             elif dl >= 2 and dl <= 5:
  7.                 total += (2 * dl)
  8.             else:
  9.                 total += (3 * dl)
  10.             
  11.         return total
  12.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-9 08:35:46 | 只看该作者
全局:
LC 3688. Bitwise OR of Even Numbers in an Array
  1. class Solution:
  2.     def evenNumberBitwiseORs(self, nums: List[int]) -> int:
  3.         FOUND = False
  4.         ans = 0

  5.         for num in nums:
  6.             if num % 2 == 0:
  7.                 FOUND = True
  8.                 ans = ans | num

  9.         if FOUND:
  10.             return ans
  11.         else:
  12.             return 0
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-9 10:47:12 | 只看该作者
全局:
LC. 3684. Maximize Sum of At Most K Distinct Elements
  1. class Solution:
  2.     def maxKDistinct(self, nums: List[int], k: int) -> List[int]:
  3.         

  4.         nums.sort(reverse = True)
  5.         ans = []

  6.         for i in range(len(nums)):
  7.             if not ans:
  8.                 ans.append(nums[i])
  9.             elif len(ans) < k and nums[i] != ans[-1]:
  10.                 ans.append(nums[i])
  11.             
  12.             if len(ans) == k: break
  13.         
  14.         return ans

  15.         
复制代码
更加 Python 一点的code
  1. class Solution:
  2.     def maxKDistinct(self, nums: List[int], k: int) -> List[int]:
  3.         # 1. 使用 set 去重,得到所有唯一的数字
  4.         unique_nums = list(set(nums))
  5.         
  6.         # 2. 从大到小排序
  7.         unique_nums.sort(reverse=True)
  8.         
  9.         # 3. 返回前 k 个(如果 unique_nums 长度小于 k,切片会自动处理,不会报错)
  10.         return unique_nums[:k]
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-9 10:48:48 | 只看该作者
全局:
LC. 3683. Earliest Time to Finish One Task
  1. class Solution:
  2.     def earliestTime(self, tasks: List[List[int]]) -> int:
  3.         ans = float('inf')

  4.         for t in tasks:
  5.             ans = min( ans, t[0] + t[1])

  6.         return ans
  7.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-9 11:00:02 | 只看该作者
全局:
LC. 3678. Smallest Absent Positive Greater Than Average

Easy 题目,但是我居然漏看了条件,必须是 postive number,所以逻辑需要加上 i > 0
  1. class Solution:
  2.     def smallestAbsent(self, nums: List[int]) -> int:
  3.         s = sum(nums)
  4.         avg = s // len(nums)
  5.         set_nums = set(nums)
  6.         curr = avg + 1
  7.         while True:
  8.             if curr not in set_nums and curr > 0:
  9.                 return curr
  10.             else:
  11.                 curr += 1
复制代码
优化下 code,其实 Smallest Positive 应该是从 1 开始!somehow 忘记了 Python 的地板除。。。向 负无穷取整的特性。



  1. import math

  2. class Solution:
  3.     def smallestAbsent(self, nums: List[int]) -> int:
  4.         s = sum(nums)
  5.         n = len(nums)
  6.         avg = s / n  # 使用浮点数除法
  7.         
  8.         # 1. 核心逻辑:找到严格大于 avg 的最小整数
  9.         # 如果 avg = 1.5, start = 2
  10.         # 如果 avg = 2.0, start = 3
  11.         start = math.floor(avg) + 1
  12.         
  13.         # 2. 必须是正整数,所以如果 start 小于 1,从 1 开始
  14.         curr = max(1, start)
  15.         
  16.         # 3. 使用 set 优化查找效率到 O(1)
  17.         num_set = set(nums)
  18.         
  19.         # 4. 暴力向上找即可。因为 nums 长度才 100,很快就能找到
  20.         while curr in num_set:
  21.             curr += 1
  22.             
  23.         return curr
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-10 09:35:03 | 只看该作者
全局:
LC. 3674. Minimum Operations to Equalize Array

乍一看 DP,仔细一看, 直接做。
  1. class Solution:
  2.     def minOperations(self, nums: List[int]) -> int:
  3.         if len(set(nums)) == 1:
  4.             return 0
  5.         else:
  6.             return 1
  7.         
复制代码
空间优化, 其实不用整个数组做 set,直接判断所有数字是不是和 第一个数字一样,不一致直接返回 1;只有到结尾都一致才返回0.
  1. class Solution:
  2.     def minOperations(self, nums: List[int]) -> int:
  3.         # 只要找到任何一个元素和第一个元素不等,就说明需要操作
  4.         for i in range(1, len(nums)):
  5.             if nums[i] != nums[0]:
  6.                 return 1
  7.         
  8.         # 如果循环结束都没触发 return,说明全相等
  9.         return 0
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-11 10:23:42 | 只看该作者
全局:
LC 3668. Restore Finishing Order
Solved
Easy
Topics
Hint
You are given an integer array order of length n and an integer array friends.

order contains every integer from 1 to n exactly once, representing the IDs of the participants of a race in their finishing order.
friends contains the IDs of your friends in the race sorted in strictly increasing order. Each ID in friends is guaranteed to appear in the order array.
Return an array containing your friends' IDs in their finishing order.



Example 1:

Input: order = [3,1,2,5,4], friends = [1,3,4]

Output: [3,1,4]

Explanation:

The finishing order is [3, 1, 2, 5, 4]. Therefore, the finishing order of your friends is [3, 1, 4].

Example 2:

Input: order = [1,4,5,3,2], friends = [2,5]

Output: [5,2]

Explanation:

The finishing order is [1, 4, 5, 3, 2]. Therefore, the finishing order of your friends is [5, 2].



Constraints:

1 <= n == order.length <= 100
order contains every integer from 1 to n exactly once
1 <= friends.length <= min(8, n)
1 <= friends[i] <= n
friends is strictly increasing

简化算法, order 本身就是完成顺序,所以按序提取即可
  1. class Solution:
  2.     def recoverOrder(self, order: List[int], friends: List[int]) -> List[int]:
  3.         # 将朋友 ID 存入哈希集合,查找时间复杂度 O(1)
  4.         friends_set = set(friends)
  5.         
  6.         # 按照 order 的顺序筛选出在 friends_set 中的元素
  7.         # 因为 order 本身就是完成顺序,所以按序提取即可
  8.         res = [person for person in order if person in friends_set]
  9.         
  10.         return res
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-11 10:34:08 | 只看该作者
全局:
3667. Sort Array By Absolute Value
Solved
Easy
Topics
Hint
You are given an integer array nums.

Rearrange elements of nums in non-decreasing order of their absolute value.

Return any rearranged array that satisfies this condition.

Note: The absolute value of an integer x is defined as:

x if x >= 0
-x if x < 0


Example 1:

Input: nums = [3,-1,-4,1,5]

Output: [-1,1,3,-4,5]

Explanation:

The absolute values of elements in nums are 3, 1, 4, 1, 5 respectively.
Rearranging them in increasing order, we get 1, 1, 3, 4, 5.
This corresponds to [-1, 1, 3, -4, 5]. Another possible rearrangement is [1, -1, 3, -4, 5].
Example 2:

Input: nums = [-100,100]

Output: [-100,100]

Explanation:

The absolute values of elements in nums are 100, 100 respectively.
Rearranging them in increasing order, we get 100, 100.
This corresponds to [-100, 100]. Another possible rearrangement is [100, -100].

我的解法太麻烦,更好的方法是,直接用内置函数,或者用 装饰者模式 (Decorate-Sort-Undecorate)
这其实就是 Python 内部 key 参数的底层思想,也被称为 DSU 模式。

思路:
装饰 (Decorate): 将数组转换为一个元组列表,元组的第一个元素是“排序依据”(绝对值),第二个是“原始值”。

排序 (Sort): 对这个元组列表进行默认排序。

去装饰 (Undecorate): 提取出原始值。

我的原始解法,太繁琐。
  1. class Solution:
  2.     def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
  3.         absSet = set()
  4.         absDict = defaultdict(list)

  5.         for n in nums:
  6.             absSet.add(abs(n))
  7.             absDict[abs(n)].append(n)

  8.         absList = [x for x in absSet]
  9.         absList.sort()

  10.         res = []
  11.         for a in absList:
  12.             res += absDict[a]
  13.         
  14.         return res

  15.         
复制代码
用 Python 内置函数 sort with key
  1. class Solution:
  2.     def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
  3.         # 直接原地排序,使用 abs 函数作为排序的依据
  4.         # 时间复杂度: O(n log n)
  5.         # 空间复杂度: O(1) 或 O(n) 取决于排序算法实现
  6.         nums.sort(key=abs)
  7.         return nums
复制代码
不用 sort with key,可以用 装饰者模式 (Decorate-Sort-Undecorate)
这其实就是 Python 内部 key 参数的底层思想,也被称为 DSU 模式。

思路:
装饰 (Decorate): 将数组转换为一个元组列表,元组的第一个元素是“排序依据”(绝对值),第二个是“原始值”。

排序 (Sort): 对这个元组列表进行默认排序。

去装饰 (Undecorate): 提取出原始值。
  1. class Solution:
  2.     def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
  3.         # 1. 构造包含 (绝对值, 原始值) 的元组列表
  4.         # 比如 [3, -1] -> [(3, 3), (1, -1)]
  5.         decorated = [(abs(x), x) for x in nums]
  6.         
  7.         # 2. 对元组进行排序
  8.         # Python 排序元组时,会先比第一个元素,若相同再比第二个
  9.         decorated.sort()
  10.         
  11.         # 3. 提取排序后的原始值
  12.         return [pair[1] for pair in decorated]
复制代码
或者最 raw 的手写 quick sort
  1. class Solution:
  2.     def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
  3.         def quick_sort(arr):
  4.             if len(arr) <= 1:
  5.                 return arr
  6.             pivot = arr[len(arr) // 2]
  7.             
  8.             # 修改这里的比较逻辑:对比的是 abs(x)
  9.             left = [x for x in arr if abs(x) < abs(pivot)]
  10.             middle = [x for x in arr if abs(x) == abs(pivot)]
  11.             right = [x for x in arr if abs(x) > abs(pivot)]
  12.             
  13.             return quick_sort(left) + middle + quick_sort(right)
  14.         
  15.         return quick_sort(nums)
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-12 11:34:19 | 只看该作者
全局:
LC  569. Median Employee Salary
Solved
Hard
Topics
conpanies icon
Companies
Hint
SQL Schema
Pandas Schema
Table: Employee

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| id           | int     |
| company      | varchar |
| salary       | int     |
+--------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the company and the salary of one employee.


Write a solution to find the rows that contain the median salary of each company. While calculating the median, when you sort the salaries of the company, break the ties by id.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Employee table:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 1  | A       | 2341   |
| 2  | A       | 341    |
| 3  | A       | 15     |
| 4  | A       | 15314  |
| 5  | A       | 451    |
| 6  | A       | 513    |
| 7  | B       | 15     |
| 8  | B       | 13     |
| 9  | B       | 1154   |
| 10 | B       | 1345   |
| 11 | B       | 1221   |
| 12 | B       | 234    |
| 13 | C       | 2345   |
| 14 | C       | 2645   |
| 15 | C       | 2645   |
| 16 | C       | 2652   |
| 17 | C       | 65     |
+----+---------+--------+
Output:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 5  | A       | 451    |
| 6  | A       | 513    |
| 12 | B       | 234    |
| 9  | B       | 1154   |
| 14 | C       | 2645   |
+----+---------+--------+
Explanation:
For company A, the rows sorted are as follows:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 3  | A       | 15     |
| 2  | A       | 341    |
| 5  | A       | 451    | <-- median
| 6  | A       | 513    | <-- median
| 1  | A       | 2341   |
| 4  | A       | 15314  |
+----+---------+--------+
For company B, the rows sorted are as follows:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 8  | B       | 13     |
| 7  | B       | 15     |
| 12 | B       | 234    | <-- median
| 11 | B       | 1221   | <-- median
| 9  | B       | 1154   |
| 10 | B       | 1345   |
+----+---------+--------+
For company C, the rows sorted are as follows:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 17 | C       | 65     |
| 13 | C       | 2345   |
| 14 | C       | 2645   | <-- median
| 15 | C       | 2645   |
| 16 | C       | 2652   |
+----+---------+--------+


Follow up: Could you solve it without using any built-in or window functions?
  1. # Write your MySQL query statement below
  2. WITH RankedEmployees AS (
  3.     SELECT
  4.         id,
  5.         company,
  6.         salary,
  7.         ROW_NUMBER() OVER(PARTITION BY company ORDER BY salary, id) AS rn,
  8.         COUNT(*) OVER(PARTITION BY company) AS total_count
  9.     FROM Employee
  10. )
  11. SELECT id, company, salary
  12. FROM RankedEmployees
  13. WHERE rn BETWEEN total_count / 2.0 AND total_count / 2.0 + 1;
复制代码
回复

使用道具 举报

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

本版积分规则

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