Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6d93cfb

Browse files
🐱(greedy): 659. 分割数组为连续子序列
1 parent 8f09dab commit 6d93cfb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎docs/algorithm/greedy/README.md‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,61 @@ class Solution:
479479
return "Dire" if len(rq) == 0 else "Radiant"
480480
```
481481

482+
## 659. 分割数组为连续子序列
483+
484+
[原题链接](https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences/)
485+
486+
### 思路
487+
488+
使用两个哈希表:
489+
490+
- 哈希表 `counter` 用于存储元素出现的次数,`counter[n]` 代表 n 出现的次数
491+
- 哈希表 `end` 用于存储以元素结尾的连续子序列(指至少包含三个连续整数的子序列)个数,`end[n]` 代表以 n 结尾的连续子序列的个数
492+
493+
**过程如下**:
494+
495+
遍历数组 `nums`:
496+
497+
- 若元素 `n` 的出现次数 `count[n] == 0`:跳过该元素
498+
- 若元素 `n` 的出现次数 `count[n] > 0`:
499+
- 存在以元素 `n - 1` 结尾的连续子序列,即 `end[n - 1] > 0`,将元素添加到该子序列的末尾,操作数据:
500+
1.`n - 1` 结尾的子序列数量减 1:`end[n - 1] -= 1`
501+
2.`n` 结尾的子序列数量加 1:`end[n] += 1`
502+
- 不存在以元素 `n - 1` 结尾的连续子序列,此时判断是否能以 `n` 作为开头构建连续子序列,即判断 `counter[n + 1]``counter[n + 2]` 的值是否均大于 0:
503+
- 若不能构成:返回 `False`
504+
- 若可以构成,操作数据:
505+
1. `n + 1` 元素数量减 1:`counter[n + 1] -= 1`
506+
2. `n + 2` 元素数量减 1:`counter[n + 2] -= 1`
507+
3.`n + 2` 元素结尾的子序列数量加 1:`end[n + 2] += 1`
508+
509+
```python
510+
class Solution:
511+
def isPossible(self, nums: List[int]) -> bool:
512+
# 记录元素出现次数
513+
counter = dict()
514+
for n in nums:
515+
counter[n] = counter.get(n, 0) + 1
516+
517+
end = dict()
518+
for n in nums:
519+
if counter[n] == 0:
520+
continue
521+
522+
counter[n] -= 1
523+
if end.get(n - 1, 0) > 0:
524+
# 添加到已有子序列的末尾
525+
end[n - 1] -= 1
526+
end[n] = end.get(n, 0) + 1
527+
elif counter.get(n + 1, 0) > 0 and counter.get(n + 2, 0) > 0:
528+
# 添加到子序列头部
529+
counter[n + 1] -= 1
530+
counter[n + 2] -= 1
531+
end[n + 2] = end.get(n + 2, 0) + 1
532+
else:
533+
return False
534+
return True
535+
```
536+
482537
## 955. 删列造序 II
483538

484539
[原题链接](https://leetcode-cn.com/problems/delete-columns-to-make-sorted-ii/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /