LeetCode 题解工作台
得分最高的最小轮调
给你一个数组 nums ,我们可以将它按一个非负整数 k 进行轮调,这样可以使数组变为 [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]] 的形式。此后,任何值小于或等于其索引的项都可…
2
题型
4
代码语言
3
相关题
当前训练重点
困难 · 前缀和
答案摘要
对于每个数,都有一个固定的 k 生效区间。我们先利用差分,预处理每个数的 k 生效区间。有最多个数能覆盖到的 k 即是答案。 class Solution:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个数组 nums,我们可以将它按一个非负整数 k 进行轮调,这样可以使数组变为 [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]] 的形式。此后,任何值小于或等于其索引的项都可以记作一分。
- 例如,数组为
nums = [2,4,1,3,0],我们按k = 2进行轮调后,它将变成[1,3,0,2,4]。这将记为3分,因为1 > 0[不计分]、3 > 1[不计分]、0 <= 2[计 1 分]、2 <= 3[计 1 分],4 <= 4[计 1 分]。
在所有可能的轮调中,返回我们所能得到的最高分数对应的轮调下标 k 。如果有多个答案,返回满足条件的最小的下标 k 。
示例 1:
输入:nums = [2,3,1,4,0] 输出:3 解释: 下面列出了每个 k 的得分: k = 0, nums = [2,3,1,4,0], score 2 k = 1, nums = [3,1,4,0,2], score 3 k = 2, nums = [1,4,0,2,3], score 3 k = 3, nums = [4,0,2,3,1], score 4 k = 4, nums = [0,2,3,1,4], score 3 所以我们应当选择 k = 3,得分最高。
示例 2:
输入:nums = [1,3,0,2,4] 输出:0 解释: nums 无论怎么变化总是有 3 分。 所以我们将选择最小的 k,即 0。
提示:
1 <= nums.length <= 1050 <= nums[i] < nums.length
解题思路
方法一:差分数组
对于每个数,都有一个固定的 k 生效区间。我们先利用差分,预处理每个数的 k 生效区间。有最多个数能覆盖到的 k 即是答案。
class Solution:
def bestRotation(self, nums: List[int]) -> int:
n = len(nums)
mx, ans = -1, n
d = [0] * n
for i, v in enumerate(nums):
l, r = (i + 1) % n, (n + i + 1 - v) % n
d[l] += 1
d[r] -= 1
s = 0
for k, t in enumerate(d):
s += t
if s > mx:
mx = s
ans = k
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests for efficiency with large arrays (e.g., length 10^5).
- question_mark
Ability to implement sliding window and prefix sum techniques.
- question_mark
Understanding the trade-off between recalculating and updating scores.
常见陷阱
外企场景- error
Inefficient recalculation of scores for each rotation instead of using prefix sums.
- error
Forgetting to track the smallest k when multiple rotations yield the same highest score.
- error
Not considering edge cases with small arrays or array with the same values.
进阶变体
外企场景- arrow_right_alt
Rotating arrays in other ways (e.g., left or right rotations).
- arrow_right_alt
Generalizing the score calculation to other comparison rules.
- arrow_right_alt
Applying this approach to arrays of different sizes and constraints.