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 204f091

Browse files
🐱(offer): 面试题 17.16. 按摩师
1 parent aab4c32 commit 204f091

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

‎docs/data-structure/array/README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2630,6 +2630,49 @@ func getMin(a int, b int) int {
26302630
}
26312631
```
26322632

2633+
## 945. 使数组唯一的最小增量
2634+
2635+
[原题链接](https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique/)
2636+
2637+
### 解一:计数
2638+
2639+
一开始暴力破解超时了,优化一下采用以下写法:
2640+
2641+
1. 先把重复出现的数字存储起来
2642+
2. 遍历 0~80000 的数字(最坏情况出现 40000 个 40000,最多可以叠加到 80000)
2643+
- 如果发现数字是重复出现过的:
2644+
- 将记录重复出现数字的 `repeat` 变量 + 1
2645+
- 在结果 `res` 提前减去 `重复个数 * 重复数字`
2646+
- 如果发现是空的位置:
2647+
- 用空的位置处理一个重复出现的数字:`repeat -= 1`
2648+
-`res` 加上空位的数字
2649+
2650+
```python
2651+
class Solution:
2652+
def minIncrementForUnique(self, A: List[int]) -> int:
2653+
count = [0 for _ in range(80000)]
2654+
for x in A:
2655+
count[x] += 1
2656+
2657+
# 总数
2658+
res = 0
2659+
# 重复数量
2660+
repeat = 0
2661+
2662+
for i in range(80000):
2663+
if count[i] > 1:
2664+
# 出现重复
2665+
repeat += count[i] - 1
2666+
# 减去多余的数
2667+
res -= i * (count[i] - 1)
2668+
# 没有出现过的数
2669+
if count[i] == 0 and repeat > 0:
2670+
repeat -= 1 # 处理一个重复的数
2671+
res += i
2672+
2673+
return res
2674+
```
2675+
26332676
<!-- tabs:end -->
26342677

26352678
## 1002. 查找常用字符

‎docs/offer/README.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,33 @@ func reversePrint(head *ListNode) []int {
247247
- 时间复杂度:$O(n)$
248248
- 空间复杂度:$O(n)$
249249

250+
## 面试题 17.16. 按摩师
251+
252+
[原题链接](https://leetcode-cn.com/problems/the-masseuse-lcci/)
253+
254+
### 动态规划
255+
256+
-`dp[0][i]` 表示不接 i 预约可以获得的最长预约时间
257+
-`dp[1][i]` 表示接 i 预约可以获得的最长预约时间
258+
259+
```python
260+
class Solution:
261+
def massage(self, nums: List[int]) -> int:
262+
# dp[0][i] 不接
263+
# dp[1][i] 接
264+
length = len(nums)
265+
if length == 0:
266+
return 0
267+
dp = [[0 for _ in range(length)] for _ in range(2)]
268+
# 转移方程:dp[0][i] = max(dp[1][i - 1], dp[0][i - 1])
269+
# dp[1][i] = max(dp[0][i - 1] + nums[i])
270+
dp[1][0] = nums[0]
271+
for i in range(1, length):
272+
dp[0][i] = max(dp[1][i - 1], dp[0][i - 1])
273+
dp[1][i] = dp[0][i - 1] + nums[i]
274+
return max(dp[0][length - 1], dp[1][length - 1])
275+
```
276+
250277
## 面试题24. 反转链表
251278

252279
[原题链接](https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/)

0 commit comments

Comments
(0)

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