Skip to content

Commit 35c96b5

Browse files
committed
feat(docs): i18n Leetcode 目录翻译完成 (42 篇)
translator-leetcode 产出。Leetcode 题解目录特殊处理: - 原文件名含方括号/中文/空格/_translated 后缀,命名风格混乱 - 翻译版统一改为 kebab-case 英文 slug: [146]LRU 缓存_translated.md → 146-lru-cache.en.md [121]买卖股票的最佳时期_translated.md → 121-best-time-to-buy-and-sell-stock.en.md 双向翻译: - zh→en: 35 篇(绝大多数原文是中文题解) - en→zh: 7 篇(2241 ATM / 2270 Split Array / 3138 Anagram / 46 全排列 / 9021 TUT / 93 IP / Counting Stars / 等英文原文) 代码块(Python/C++/Java)原样保留,仅译注释。LaTeX 公式保留。 frontmatter 继承原文 docId,带 translatedFrom 标记。 跳过:1 个 <Cards> 索引页。
1 parent 07bd538 commit 35c96b5

42 files changed

Lines changed: 3419 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
---
2+
title: "1004. Max Consecutive Ones III"
3+
date: "2022.12.07-01:15"
4+
tags:
5+
- - Python
6+
- - solved
7+
- answer
8+
abbrlink: ed19b576
9+
docId: ytg2bds2dnhzw37nrb3vassy
10+
lang: en
11+
translatedFrom: zh
12+
translatedAt: 2026-04-15T12:00:00Z
13+
translatorAgent: claude-sonnet-4-6
14+
---
15+
16+
Today's daily problem was too hard, so I picked one myself. The approach is hash table + sliding window, though it feels like only sliding window was really used.
17+
18+
```python
19+
20+
class Solution:
21+
def longestOnes(self, nums: List[int], k: int) -> int:
22+
k_mean = k
23+
# Used to record how many arrays there are now
24+
flag = 0
25+
# Used to record the maximum land number
26+
max_flag = 0
27+
for start in range(len(nums)):
28+
tail = start
29+
while k >= 0 and tail <= len(nums) - 1:
30+
if nums[tail] == 1:
31+
tail += 1
32+
flag += 1
33+
elif nums[tail] == 0 and k > 0:
34+
tail += 1
35+
k -= 1
36+
flag += 1
37+
elif nums[tail] == 0 and k == 0:
38+
k = k_mean
39+
max_flag = max(max_flag, flag)
40+
flag = 0
41+
break
42+
if tail == len(nums):
43+
max_flag = max(max_flag, flag)
44+
flag = 0
45+
break
46+
return max_flag
47+
```
48+
49+
This was my initial approach. Although it uses two pointers, it lacks flexibility — feels very stiff.
50+
51+
The following is from [@Lincoln](/u/lincoln), recorded here purely as a personal note, not presented as my own answer.
52+
53+
```
54+
class Solution:
55+
def longestOnes(self, nums: List[int], k: int) -> int:
56+
"""
57+
Idea: 1. k=0 can be understood as finding the longest substring without duplicates
58+
2. If (current window size - number of 1s in window) <= k: expand the window (right+1)
59+
If (current window size - number of 1s in window) > k: slide the window right (left+1)
60+
Method: Hash table + Sliding window
61+
"""
62+
n = len(nums)
63+
o_res = 0
64+
left = right = 0
65+
while right < n:
66+
if nums[right]== 1: o_res += 1
67+
if right-left+1- o_res > k:
68+
if nums[left]== 1: o_res -= 1
69+
left += 1
70+
right += 1
71+
return right - left
72+
```
73+
74+
Lincoln's thinking is very clear — worth remembering.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
title: "121. Best Time to Buy and Sell Stock"
3+
date: "2024.01.01 0:00"
4+
tags:
5+
- Python
6+
- answer
7+
- Array
8+
- Dynamic planning
9+
abbrlink: 3a21fe32
10+
docId: w9ffo1wycpbz50051cb7lyo5
11+
lang: en
12+
translatedFrom: zh
13+
translatedAt: 2026-04-15T12:00:00Z
14+
translatorAgent: claude-sonnet-4-6
15+
---
16+
17+
# Problem
18+
19+
[121. Best Time to Buy and Sell Stock](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/)
20+
21+
# Approach
22+
23+
Dynamic programming — find the minimum problem.
24+
25+
Recurrence: the maximum profit on day `i` = max(maximum profit on day `i-1`, price on day `i` − minimum price before day `i`)
26+
27+
# Code
28+
29+
```python
30+
class Solution:
31+
def maxProfit(self, prices: List[int]) -> int:
32+
# Recurrence: max profit on day i = max(max profit on day i-1, price on day i - min price before day i-1)
33+
dp = [0] * len(prices)
34+
min_price = prices[0]
35+
for i in range(1, len(prices)):
36+
dp[i] = max(dp[i - 1], prices[i] - min_price)
37+
min_price = min(min_price, prices[i])
38+
return dp[-1]
39+
```
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
title: "1234. Replace the Substring for Balanced String — Daily Problem"
3+
date: "2024.01.01 0:00"
4+
tags:
5+
- - Python
6+
- - answer
7+
abbrlink: 56d97dcf
8+
docId: p8igr19xfxnuyo2lpngnr6fg
9+
lang: en
10+
translatedFrom: zh
11+
translatedAt: 2026-04-15T12:00:00Z
12+
translatorAgent: claude-sonnet-4-6
13+
---
14+
15+
# Problem
16+
17+
[1234. Replace the Substring for Balanced String](https://leetcode.cn/problems/replace-the-substring-for-balanced-string/description/)
18+
19+
# Approach
20+
21+
`all()`: returns `True` if `bool(x)` is `True` for all values `x` in the iterable. Returns `True` if the iterable is empty.
22+
23+
Two pointers in the same direction — the elegant solution for this problem.
24+
25+
If every character in the string appears exactly `n/4` times, then it is a "balanced string."
26+
27+
If any character **outside** the substring to be replaced appears more than $m = \dfrac{n}{4}$ times, then no matter how you replace the substring, you cannot make that character's count equal to `m`.
28+
29+
Conversely, if every character **outside** the substring appears at most `m` times:
30+
31+
> Then a replacement exists that makes `s` a balanced string, where each character appears exactly `m` times.
32+
> For this problem, let the left and right endpoints of the substring be `left` and `right`. Enumerate `right`:
33+
> if every character outside the substring has count ≤ m, then the substring from `left` to `right` is a valid replacement. Its length is `right − left + 1`.
34+
> Update the minimum answer, then move `left` right to shrink the substring length.
35+
36+
# Code
37+
38+
```python
39+
class Solution:
40+
def balancedString(self, s: str) -> int:
41+
s_c = Counter(s)
42+
n = len(s)
43+
if all(s_c[v] <= n//4 for v in s_c):
44+
return 0
45+
ans, left = inf, 0
46+
# enumerate right endpoint
47+
for i, j in enumerate(s):
48+
s_c[j] -= 1
49+
while all(s_c[v] <= n // 4 for v in s_c):
50+
ans = min(ans, i - left + 1)
51+
s_c[s[left]] += 1
52+
left += 1
53+
return ans
54+
55+
```
56+
57+
```go
58+
func balancedString(s string) int {
59+
cnt, m := ['X']int{}, len(s)/4
60+
for _, c := range s {
61+
cnt[c]++
62+
}
63+
if cnt['Q'] == m && cnt['W'] == m && cnt['E'] == m && cnt['R'] == m {
64+
return 0
65+
}
66+
ans, left := len(s), 0
67+
for right, c := range s {
68+
cnt[c]--
69+
for cnt['Q'] <= m && cnt['W'] <= m && cnt['E'] <= m && cnt['R'] <= m {
70+
ans = min(ans, right-left+1)
71+
cnt[s[left]]++
72+
left++
73+
}
74+
}
75+
return ans
76+
}
77+
func min(a, b int) int { if a > b { return b }; return a }
78+
```
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
title: "1333. Filter Restaurants by Vegan-Friendly, Price, and Distance"
3+
date: "2024.01.01 0:00"
4+
tags:
5+
- Python
6+
- answer
7+
- Sort
8+
- Array
9+
abbrlink: 7f1331bc
10+
docId: jcqhknk5z2xr3rfqn49me4j9
11+
lang: en
12+
translatedFrom: zh
13+
translatedAt: 2026-04-15T12:00:00Z
14+
translatorAgent: claude-sonnet-4-6
15+
---
16+
17+
# Problem
18+
19+
[1333. Filter Restaurants by Vegan-Friendly, Price, and Distance](https://leetcode-cn.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/)
20+
21+
# Approach
22+
23+
My initial approach used `pop()`, but the time complexity was too high (~400ms). I switched to a list comprehension.
24+
25+
A senior once told me: `pop()` runtime is fine, but when you combine it with index operations inside, it becomes very slow.
26+
27+
**`sorted` and `lambda` usage:**
28+
29+
`lambda` is Python's anonymous function syntax. Here, `lambda x: (x[1], x[0])` defines a function that takes an element `x` (a sublist of `restaurants`) and returns a tuple `(x[1], x[0])`.
30+
31+
This means sorting is first based on `x[1]` (rating), then by `x[0]` (id) if `x[1]` values are equal.
32+
33+
```python
34+
while ind < len(restaurants):
35+
i = restaurants[ind]
36+
if veganFriendly == 1 and i[2] == 0:
37+
restaurants.pop(ind)
38+
elif maxPrice < i[3]:
39+
restaurants.pop(ind)
40+
elif maxDistance < i[4]:
41+
restaurants.pop(ind)
42+
else:
43+
ind += 1
44+
```
45+
46+
# Code
47+
48+
```python
49+
class Solution:
50+
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> \
51+
List[int]:
52+
restaurants = [
53+
i for i in restaurants
54+
if (veganFriendly == 0 or i[2] == veganFriendly)
55+
and i[3] <= maxPrice
56+
and i[4] <= maxDistance
57+
]
58+
restaurants = sorted(restaurants, key=lambda x: (x[1], x[0]), reverse=True)
59+
return [i[0] for i in restaurants]
60+
```
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
---
2+
title: "142. Linked List Cycle II"
3+
date: "2024.01.01 0:00"
4+
tags:
5+
- - Python
6+
- - answer
7+
abbrlink: e2c9cca9
8+
docId: ylpucy1rbbnfpe3t62u8kcfq
9+
lang: en
10+
translatedFrom: zh
11+
translatedAt: 2026-04-15T12:00:00Z
12+
translatorAgent: claude-sonnet-4-6
13+
---
14+
15+
[142. Linked List Cycle II](https://leetcode.cn/problems/linked-list-cycle-ii/)
16+
17+
# Approach
18+
19+
### Problem Analysis
20+
21+
This type of linked list problem is generally solved using the two-pointer technique — for example, finding the node at distance K from the tail, finding the cycle entrance, or finding the intersection node.
22+
23+
### Algorithm
24+
25+
1. **First meeting of two pointers:** Set two pointers `fast` and `slow` both pointing to `head`. `fast` moves 2 steps per round, `slow` moves 1 step per round.
26+
27+
a. **Case 1:** If `fast` reaches the end of the list, the list has no cycle — return `null`.
28+
29+
**Tip:** If there is a cycle, the two pointers will definitely meet. Each round, the gap between `fast` and `slow` decreases by 1, so `fast` will eventually catch `slow`.
30+
31+
b. **Case 2:** When `fast == slow`, the two pointers **meet for the first time inside the cycle**. Let's analyze the steps taken:
32+
33+
Suppose the list has `a + b` nodes in total, with `a` nodes from the head to the cycle entrance (not counting the entrance node), and `b` nodes in the cycle. Let `f` and `s` be the steps taken by each pointer:
34+
- `fast` travels twice the steps of `slow`: `f = 2s`
35+
- `fast` travels `n` extra cycles compared to `slow`: `f = s + nb`
36+
- From the above: `f = 2nb`, `s = nb` — both pointers have walked an integer multiple of the cycle length.
37+
38+
2. **Current situation analysis:**
39+
40+
If a pointer walks `k` steps from `head`, it reaches the cycle entrance when `k = a + nb` (after `a` steps it reaches the entrance; each additional cycle of `b` steps brings it back to the entrance).
41+
42+
Currently, `slow` has walked `nb` steps. So we just need `slow` to walk `a` more steps to reach the cycle entrance.
43+
44+
But we don't know `a`. We use a second pointer starting from `head`. When this pointer and `slow` both walk `a` steps together, they meet exactly at the cycle entrance.
45+
46+
3. **Second meeting of two pointers:**
47+
Keep `slow` in place, reset `fast` to `head`. Both move forward 1 step per round.
48+
49+
When `fast` has walked `a` steps: `slow` has walked `a + nb` steps. The two pointers meet and both point to the **cycle entrance**.
50+
51+
4. Return the node pointed to by `slow`.
52+
53+
### Complexity Analysis
54+
55+
**Time complexity O(N):** In the second encounter, the slow pointer walks `a < a + b` steps. In the first encounter, the slow pointer walks `a + b − x < a + b` steps (where `x` is the distance from the meeting point to the entrance). The overall complexity is linear.
56+
57+
**Space complexity O(1):** The two pointers use constant extra space.
58+
59+
# Code
60+
61+
```python
62+
class Solution:
63+
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
64+
a = head
65+
b = head
66+
while True:
67+
if not b or not b.next:
68+
return None
69+
a = a.next
70+
b = b.next.next
71+
if b == a:
72+
break
73+
b = head
74+
while a != b:
75+
a, b = a.next, b.next
76+
return b
77+
```
78+
79+
```cpp
80+
class Solution {
81+
public:
82+
ListNode *detectCycle(ListNode *head) {
83+
ListNode *a = head;
84+
ListNode *b = head;
85+
while (true) {
86+
if (!b or !b->next) {
87+
return nullptr;
88+
}
89+
a = a->next;
90+
b = b->next->next;
91+
// because b moves two steps each time, a and b must meet
92+
if (a == b) {
93+
break;
94+
}
95+
}
96+
// After meeting, keep a in place, reset b to head
97+
b = head;
98+
while(a!=b){
99+
a = a->next;
100+
b = b->next;
101+
}
102+
103+
return a;
104+
}
105+
};
106+
```

0 commit comments

Comments
 (0)