得分最高的最小轮调
难度:
标签:
题目描述
You are given an array nums
. You can rotate it by a non-negative integer k
so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]
. Afterward, any entries that are less than or equal to their index are worth one point.
- For example, if we have
nums = [2,4,1,3,0]
, and we rotate byk = 2
, it becomes[1,3,0,2,4]
. This is worth3
points because1 > 0
[no points],3 > 1
[no points],0 <= 2
[one point],2 <= 3
[one point],4 <= 4
[one point].
Return the rotation index k
that corresponds to the highest score we can achieve if we rotated nums
by it. If there are multiple answers, return the smallest such index k
.
Example 1:
Input: nums = [2,3,1,4,0] Output: 3 Explanation: Scores for each k are listed below: 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 So we should choose k = 3, which has the highest score.
Example 2:
Input: nums = [1,3,0,2,4] Output: 0 Explanation: nums will always have 3 points no matter how it shifts. So we will choose the smallest k, which is 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] < nums.length
代码结果
运行时间: 119 ms, 内存: 29.1 MB
/*
* This function takes an array of integers and returns the index k that maximizes the score after rotating the array.
* The score is calculated based on the number of elements less than or equal to their indices.
* This solution uses Java Stream for the computation.
*/
import java.util.stream.IntStream;
public int bestRotation(int[] nums) {
int n = nums.length;
int[] change = new int[n];
// Calculate the changes needed to the score for each k
IntStream.range(0, n).forEach(i -> change[(i - nums[i] + 1 + n) % n]--);
// Calculate the prefix sum array
IntStream.range(1, n).forEach(i -> change[i] += change[i - 1] + 1);
// Find the index with the maximum score
return IntStream.range(0, n).reduce((a, b) -> change[a] > change[b] ? a : b).getAsInt();
}
解释
方法:
该题解采用了差分数组和前缀和的思想来解决问题。首先,创建一个长度为n的数组d,并将所有元素初始化为1。这是因为在不考虑特殊情况下,每个元素至少可以贡献1分。然后,对于数组nums中的每个元素x,计算它在轮调后可能导致分数减少的位置,即当x被移到其索引之后时,它将不再贡献分数。因此,我们在数组d的相应位置上减去1。接下来,使用累积和函数accumulate来计算数组d的前缀和,这样每个元素d[i]就表示在轮调k=i时的得分。最后,返回得分最高的轮调下标k,即d中最大元素的索引。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在初始化数组d时,所有元素的初始值设置为1?是否意味着每个元素默认都能贡献1分?
▷🦆
在计算元素x可能导致分数减少的位置时,为什么选择使用(i + n - x + 1) % n作为索引来更新数组d?这个表达式具体是如何推导出来的?
▷🦆
实现中提到的`累积和函数accumulate`的具体工作原理是什么?它是如何帮助计算每个轮调下标得分的?
▷