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

刷题记录帖子

🔗
 楼主| Myron2017 2026-7-13 05:04:48 | 只看该作者
全局:
LC. 3978. Unique Middle Element

我的解法
  1. class Solution:
  2.     def isMiddleElementUnique(self, nums: list[int]) -> bool:
  3.         freq = Counter(nums)

  4.         return freq[nums[len(nums)// 2]]  == 1
  5.         
复制代码
可以优化的地方,

我们真的需要统计所有元素的频率吗?其实不需要。我们只关心中间那个元素出现了几次。因此,我们可以先找出中间元素的值,然后再遍历一次数组,只数这一个值的出现次数。
  1. class Solution:
  2.     def isMiddleElementUnique(self, nums: list[int]) -> bool:
  3.         # 1. 找到中间元素的值
  4.         mid_val = nums[len(nums) // 2]
  5.         
  6.         # 2. 统计这个值在数组中出现的次数
  7.         return nums.count(mid_val) == 1
复制代码
不用内置函数,注意可以提前截断。
  1. class Solution:
  2.     def isMiddleElementUnique(self, nums: list[int]) -> bool:
  3.         mid_val = nums[len(nums) // 2]
  4.         count = 0
  5.         
  6.         for num in nums:
  7.             if num == mid_val:
  8.                 count += 1
  9.                 # 剪枝小技巧:如果发现次数已经大于1了,直接返回 False 即可,没必要看完
  10.                 if count > 1:
  11.                     return False
  12.                     
  13.         return count == 1
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-13 05:11:27 | 只看该作者
全局:
LC. 3982. Sum of Integers with Maximum Digit Range

我的解法
  1. class Solution:
  2.     def maxDigitRange(self, nums: list[int]) -> int:
  3.         digitRange = defaultdict(list)
  4.         max_dr = -1

  5.         for n in nums:
  6.             strn = [int(x) for x in str(n)]
  7.             dr = max(strn) - min(strn)
  8.             digitRange[dr].append(n)
  9.             max_dr = max(dr, max_dr)
  10.         
  11.         return sum(digitRange[max_dr])
复制代码
优化

核心思路:
我们其实并不关心那些较小的 Digit Range 对应的数字是什么。我们可以像“打擂台”一样,在遍历数组的时候,只维护两个变量:

历史最大的 max_dr。

这个 max_dr 对应的累加和 ans_sum。

如果遇到了更大的 dr,就清空之前的和,重新开始累加;如果遇到了相等的 dr,就加到当前的和里。
  1. class Solution:
  2.     def maxDigitRange(self, nums: list[int]) -> int:
  3.         max_dr = -1
  4.         ans_sum = 0

  5.         for n in nums:
  6.             # 技巧 1:转成字符串
  7.             s = str(n)
  8.             # 技巧 2:直接用 max() 和 min() 获取最大最小字符,再转回 int 计算
  9.             dr = int(max(s)) - int(min(s))

  10.             if dr > max_dr:
  11.                 # 遇到新的更大范围,刷新 max_dr,并重置当前求和
  12.                 max_dr = dr
  13.                 ans_sum = n
  14.             elif dr == max_dr:
  15.                 # 遇到一样的最大范围,累加进结果里
  16.                 ans_sum += n
  17.                
  18.         return ans_sum
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-13 05:20:23 | 只看该作者
全局:
LC. 3986. Number of Elapsed Seconds Between Two Times

You are given two valid times startTime and endTime, each represented as a string in the format "HH:MM:SS".

Return the number of seconds that have elapsed from startTime to endTime.



Example 1:

Input: startTime = "01:00:00", endTime = "01:00:25"

Output: 25

Explanation:

endTime is 25 seconds ahead of startTime.
Example 2:

Input: startTime = "12:34:56", endTime = "13:00:00"

Output: 1504

Explanation:

endTime is 25 minutes and 4 seconds ahead of startTime, which equals 1504 seconds.



Constraints:

startTime.length == 8
endTime.length == 8
startTime and endTime are valid times in the format "HH:MM:SS"
00 <= HH <= 23
00 <= MM <= 59
00 <= SS <= 59
endTime is not earlier than startTime

我的解法

class Solution:
    def secondsBetweenTimes(self, startTime: str, endTime: str) -> int:
        start_seconds = 3600 * (10 * int(startTime[0]) + int(startTime[1])) + 60 * (10 * int(startTime[3]) + int(startTime[4])) + (10* int(startTime[6]) + int(startTime[7]))
        end_seconds = 3600 * (10 * int(endTime[0]) + int(endTime[1])) + 60 * (10 * int(endTime[3]) + int(endTime[4])) + (10* int(endTime[6]) + int(endTime[7]))

        return end_seconds -  start_seconds


一个优化点,可以用 map 来分割字符。

同时

在 Python 中,int() 函数对字符串转换非常“宽容”,它会自动忽略前面的前导零。

你可以放心地看这几个例子:

Python
int('01')    # 返回: 1
int('007')   # 返回: 7
int('0000')  # 返回: 0
  1. class Solution:
  2.     def secondsBetweenTimes(self, startTime: str, endTime: str) -> int:
  3.         # 定义一个辅助函数,专门负责把 "HH:MM:SS" 转成总秒数
  4.         def get_seconds(time_str: str) -> int:
  5.             h, m, s = map(int, time_str.split(':'))
  6.             return h * 3600 + m * 60 + s
  7.             
  8.         return get_seconds(endTime) - get_seconds(startTime)
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-16 11:55:45 | 只看该作者
全局:
LC. 3452. Sum of Good Numbers

Hint
Given an array of integers nums and an integer k, an element nums[i] is considered good if it is strictly greater than the elements at indices i - k and i + k (if those indices exist). If neither of these indices exists, nums[i] is still considered good.

Return the sum of all the good elements in the array.



Example 1:

Input: nums = [1,3,2,1,5,4], k = 2

Output: 12

Explanation:

The good numbers are nums[1] = 3, nums[4] = 5, and nums[5] = 4 because they are strictly greater than the numbers at indices i - k and i + k.

Example 2:

Input: nums = [2,1], k = 1

Output: 2

Explanation:

The only good number is nums[0] = 2 because it is strictly greater than nums[1].



Constraints:

2 <= nums.length <= 100
1 <= nums[i] <= 1000
1 <= k <= floor(nums.length / 2)

我的解法,其实我写的时候就感觉写复杂了,不过没想清楚怎么简化,就先通过再说了。
  1. class Solution:
  2.     def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
  3.         ans = 0
  4.         n = len(nums)

  5.         for i in range(n):
  6.             
  7.             if i-k < 0 and i+k >= n:
  8.                 ans += nums[i]
  9.             else:
  10.                 n1, n2 = 1001, 1001
  11.                 if i-k >= 0: n1 = nums[i-k]
  12.                 if i+k < n:  n2 = nums[i+k]
  13.                 if n1 == 1001 and n2 < nums[i]:
  14.                     ans += nums[i]
  15.                 if n2 == 1001 and n1 < nums[i]:
  16.                     ans += nums[i]
  17.                 if n1 < nums[i] and n2 < nums[i]:
  18.                     ans += nums[i]
  19.             
  20.         return ans
  21.         
复制代码
优化,主要是两个一个是边界条件合并,巧妙利用 Python 条件判断,A or B 如果 A 为 True 会短路 B;另一个是取消 magic number 1001.
  1. class Solution:
  2.     def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
  3.         ans = 0
  4.         n = len(nums)
  5.         
  6.         for i in range(n):
  7.             # 检查左边:要么索引越界(天然满足),要么当前元素严格大于左边元素
  8.             left_ok = (i - k < 0) or (nums[i] > nums[i - k])
  9.             
  10.             # 检查右边:要么索引越界(天然满足),要么当前元素严格大于右边元素
  11.             right_ok = (i + k >= n) or (nums[i] > nums[i + k])
  12.             
  13.             # 只有两边都满足,才加到结果里
  14.             if left_ok and right_ok:
  15.                 ans += nums[i]
  16.                
  17.         return ans
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-18 10:38:49 | 只看该作者
全局:
LC. 1979. Find Greatest Common Divisor of Array

好久不碰了,辗转相除法都忘了。。。
  1. class Solution:
  2.     def findGCD(self, nums: List[int]) -> int:
  3.         #return math.gcd(max(nums), min(nums))

  4.         n_max, n_min = max(nums), min(nums)

  5.         while n_min != 0:
  6.             n_max, n_min  = n_min, n_max % n_min
  7.         
  8.         return n_max
  9.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-21 13:45:49 | 只看该作者
全局:
LC. 3992. Rearrange String to Avoid Character Pair

You are given a string s and two distinct lowercase English letters x and y.

Rearrange the characters of s to construct a new string t such that:

t is a permutation of s.
Every occurrence of y appears before every occurrence of x in t.
Return any valid string t.



Example 1:

Input: s = "aabc", x = "a", y = "c"

Output: "cbaa"

Explanation:

The string "cbaa" is a permutation of "aabc", and every occurrence of 'c' appears before every occurrence of 'a'.

Example 2:

Input: s = "dcab", x = "d", y = "b"

Output: "cabd"

Explanation:

The string "cabd" is a permutation of "dcab", and every occurrence of 'b' appears before every occurrence of 'd'.

Example 3:

Input: s = "axe", x = "o", y = "x"

Output: "axe"

Explanation:

The string "axe" is already valid. Since 'o' does not occur in the string, the required condition is automatically satisfied.



Constraints:

1 <= s.length <= 100
s consists of lowercase English letters.
x and y are lowercase English letters.
x != y

我的解法
  1. class Solution:
  2.     def rearrangeString(self, s: str, x: str, y: str) -> str:
  3.         freq = Counter(s)
  4.         ans = []
  5.         ans += (freq[y] * [y])
  6.         for n in freq:
  7.             if n != y:
  8.                 ans += (freq[n] * [n])

  9.         return "".join(ans)
  10.         
复制代码
优化下

列表乘法的开销:freq[y] * [y] 会生成一个类似 ['y', 'y', 'y'] 的列表。既然最终我们只需要字符串,其实可以直接用字符串相乘 "y" * freq[y] 会更轻量。
  1. from collections import Counter

  2. class Solution:
  3.     def rearrangeString(self, s: str, x: str, y: str) -> str:
  4.         freq = Counter(s)
  5.         # 直接用字符串拼接,省去 list 转 string 的开销
  6.         ans = y * freq[y]
  7.         for char, count in freq.items():
  8.             if char != y:
  9.                 ans += char * count
  10.         return ans
复制代码
解法一:极致简洁 API 魔法(推荐 ⭐⭐⭐⭐⭐)
利用 Python 底层 C 语言优化过的字符串方法 count() 和 replace(),直接一行搞定:
  1. class Solution:
  2.     def rearrangeString(self, s: str, x: str, y: str) -> str:
  3.         # y * 频次 + s中剔除掉y之后剩下的部分
  4.         return y * s.count(y) + s.replace(y, "")
复制代码
解法二:双指针 / 列表推导式 (体现基础扎实)
如果你碰到的面试官比较严格,不让你用内置的 replace 方法,可以用列表推导式写出一次遍历拼接的感觉:
  1. class Solution:
  2.     def rearrangeString(self, s: str, x: str, y: str) -> str:
  3.         # 扫描两遍:第一遍拿出所有的 y,第二遍拿出所有非 y 的字符
  4.         return "".join([c for c in s if c == y] + [c for c in s if c != y])
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-22 08:22:21 | 只看该作者
全局:
LC. 3516. Find Closest Person

Companies
Hint
You are given three integers x, y, and z, representing the positions of three people on a number line:

x is the position of Person 1.
y is the position of Person 2.
z is the position of Person 3, who does not move.
Both Person 1 and Person 2 move toward Person 3 at the same speed.

Determine which person reaches Person 3 first:

Return 1 if Person 1 arrives first.
Return 2 if Person 2 arrives first.
Return 0 if both arrive at the same time.
Return the result accordingly.



Example 1:

Input: x = 2, y = 7, z = 4

Output: 1

Explanation:

Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.
Person 2 is at position 7 and can reach Person 3 in 3 steps.
Since Person 1 reaches Person 3 first, the output is 1.

Example 2:

Input: x = 2, y = 5, z = 6

Output: 2

Explanation:

Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.
Person 2 is at position 5 and can reach Person 3 in 1 step.
Since Person 2 reaches Person 3 first, the output is 2.

Example 3:

Input: x = 1, y = 5, z = 3

Output: 0

Explanation:

Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.
Person 2 is at position 5 and can reach Person 3 in 2 steps.
Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.



Constraints:

1 <= x, y, z <= 100

简单题
  1. class Solution:
  2.     def findClosest(self, x: int, y: int, z: int) -> int:
  3.         s1 = abs(x - z)
  4.         s2 = abs(y - z)

  5.         if s1 < s2:
  6.             return 1
  7.         elif s1 > s2:
  8.             return 2
  9.         else:
  10.             return 0
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-25 08:56:24 | 只看该作者
全局:
3560. Find Minimum Log Transportation Cost

You are given integers n, m, and k.

There are two logs of lengths n and m units, which need to be transported in three trucks where each truck can carry one log with length at most k units.

You may cut the logs into smaller pieces, where the cost of cutting a log of length x into logs of length len1 and len2 is cost = len1 * len2 such that len1 + len2 = x.

Return the minimum total cost to distribute the logs onto the trucks. If the logs don't need to be cut, the total cost is 0.



Example 1:

Input: n = 6, m = 5, k = 5

Output: 5

Explanation:

Cut the log with length 6 into logs with length 1 and 5, at a cost equal to 1 * 5 == 5. Now the three logs of length 1, 5, and 5 can fit in one truck each.

Example 2:

Input: n = 4, m = 4, k = 6

Output: 0

Explanation:

The two logs can fit in the trucks already, hence we don't need to cut the logs.



Constraints:

2 <= k <= 105
1 <= n, m <= 2 * k
The input is generated such that it is always possible to transport the logs.

这道题目是 easy 是因为加了限制条件,两段木头,三辆车 == 》 这表示最多只能切一刀

There are two logs of lengths n and m units, which need to be transported in three trucks where each truck can carry one log with length at most k units.


所以我的解法
  1. class Solution:
  2.     def minCuttingCost(self, n: int, m: int, k: int) -> int:
  3.         cost = 0

  4.         while n > k:
  5.             cost += (k * (n-k))
  6.             n -= k
  7.         
  8.         while m > k:
  9.             cost += (k * (m-k))
  10.             m -= k

  11.         return cost
复制代码
循环只进入一次。
  1. class Solution:
  2.     def minCuttingCost(self, n: int, m: int, k: int) -> int:
  3.         # 因为最多有3辆车,2根木头,所以最多只会有一根木头大于 k,且最多切一刀
  4.         if n > k:
  5.             return k * (n - k)
  6.         if m > k:
  7.             return k * (m - k)
  8.         return 0
复制代码
这个就是变成了 x * ( L - x ) 最小的问题,根据函数性质,当然是两个切割的结果差尽可能大的时候总乘积小。
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-25 09:00:03 来自APP | 只看该作者
全局:
但是题目的数学证明并不普通。
切割不变量定理(Cutting Invariant)。

回复

使用道具 举报

🔗
 楼主| Myron2017 2026-7-25 09:04:53 来自APP | 只看该作者
全局:
升级题目是
题目升级:给你一整组木头(数组)和一整组不同的卡车容量, 怎么做
直接给出结论:数学底层逻辑完全没变——我们依然要追求“让最终切出来的木头碎块平方和 $\sum p_i^2$ 最大化”。但算法模型会根据卡车的容量限制是否严苛,分化为“贪心 / 双指针排序”和“状态压缩 DP”两个方向。

算法模型拆解:两种面试场景场景 A:卡车数量充足(贪心 + 双排序)—— LeetCode Medium 难度如果题目保证卡车足够多、容量也够大(只要总容量 > 总木头长度就一定能装下),这题就是一个非常优美的贪心匹配问题。核心思路为了制造出最大的碎块,我们应该把最长的木头,匹配给容量最大的卡车去装或者去切!

(1) 把 logs(木头数组)降序排序。
(2) 把 trucks(卡车容量数组)降序排序。
(3) 每次取最大的木头 L$和最大的卡车容量 C:如果 L < C:不用切,这根木头直接整根装进这个大卡车(省下最大的平方和)。如果 L > C:贪心一刀切出一个长度为 C 的碎块装进卡车,剩下 L - C 的长度放回木头数组中,继续去跟下一辆卡车匹配。

(贪心排序 + 堆/模拟)

import heapq from typing import List

class Solution: def minTotalCuttingCost(self, logs: List[int], trucks: List[int]) -> int:
    # 1. 降序排序卡车容量(最能装的卡车放前面)
    trucks.sort(reverse=True)

    # 2. 为了方便每次取出“当前最长的木头”,我们使用最大堆(Python的heapq是小顶堆,取负号模拟)
    max_heap = [-log for log in logs]
    heapq.heapify(max_heap)
   
    total_cost = 0
   
    for capacity in trucks:
        if not max_heap:
            break
            
        # 取出当前最长的一根木头
        longest_log = -heapq.heappop(max_heap)
        
        if longest_log <= capacity:
            # 能够整根放进去,不需要切割,产生 0 花费
            continue
        else:
            # 贪心:切出卡车能装下的最大长度 capacity
            # 切割花费 = 切下来的一块 * 剩下的一块
            remain = longest_log - capacity
            total_cost += capacity * remain
            
            # 把剩下的木头扔回堆里,参与后续卡车的分配
            heapq.heappush(max_heap, -remain)
            
    return total_cost
回复

使用道具 举报

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

本版积分规则

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