[LeetCode]Smallest Rotation with Highest Score

题目描述:

LeetCode 798. Smallest Rotation with Highest Score

 Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1].  Afterward, any entries that are less than or equal to their index are worth 1 point. 

For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, it becomes [1, 3, 0, 2, 4].  This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].

Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive.  If there are multiple answers, return the smallest such index K.

Example 1:
Input: [2, 3, 1, 4, 0]
Output: 3
Explanation:  
Scores for each K are listed below: 
K = 0,  A = [2,3,1,4,0],    score 2
K = 1,  A = [3,1,4,0,2],    score 3
K = 2,  A = [1,4,0,2,3],    score 3
K = 3,  A = [4,0,2,3,1],    score 4
K = 4,  A = [0,2,3,1,4],    score 3

So we should choose K = 3, which has the highest score.

Example 2:
Input: [1, 3, 0, 2, 4]
Output: 0
Explanation:  A will always have 3 points no matter how it shifts.
So we will choose the smallest K, which is 0.

Note:

  • A will have length at most 20000.
  • A[i] will be in the range [0, A.length].

题目大意:

数组A是0 ~ N - 1的排列

对分值mark进行如下定义:

mark[i] = 1 if A[i] <= i

mark[i] = 0 otherwise

将数组A从下标K处进行旋转,求使得mark的和最大化的K值。

解题思路:

一次遍历求出分值mark的和,记为ans;按照各元素及其下标之差计数,记为cnts

从后向前遍历A,将A的末尾元素依次平移至A的首部,更新cnts和ans

Python代码:

class Solution(object):
    def bestRotation(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        cnts = collections.defaultdict(int)
        ans = 0
        for i, n in enumerate(A):
            cnts[n - i] += 1
            ans += n <= i
        bestAns, bestIdx = ans, 0
        for x in range(len(A) - 1, -1, -1):
            y = len(A) - x - 1
            if A[x] <= x + y: ans -= 1
            if A[x] == 0: ans += 1
            cnts[A[x] - x] -= 1
            ans += cnts[y + 1]
            if ans >= bestAns:
                bestAns = ans
                bestIdx = x
            cnts[A[x] + y + 1] += 1
        return bestIdx

 

本文链接:http://bookshadow.com/weblog/2018/03/11/leetcode-smallest-rotation-with-highest-score/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论