★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-aaktmlqx-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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. git
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].github
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:less
A
will have length at most 20000
.A[i]
will be in the range [0, A.length]
.給定一個數組 A
,咱們能夠將它按一個非負整數 K
進行輪調,這樣能夠使數組變爲 A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]
的形式。此後,任何值小於或等於其索引的項均可以記做一分。spa
例如,若是數組爲 [2, 4, 1, 3, 0]
,咱們按 K = 2
進行輪調後,它將變成 [1, 3, 0, 2, 4]
。這將記做 3 分,由於 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]。code
在全部可能的輪調中,返回咱們所能獲得的最高分數對應的輪調索引 K。若是有多個答案,返回知足條件的最小的索引 K。htm
示例 1: 輸入:[2, 3, 1, 4, 0] 輸出:3 解釋: 下面列出了每一個 K 的得分: 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 因此咱們應當選擇 K = 3,得分最高。
示例 2: 輸入:[1, 3, 0, 2, 4] 輸出:0 解釋: A 不管怎麼變化老是有 3 分。 因此咱們將選擇最小的 K,即 0。
提示:blog
A
的長度最大爲 20000
。A[i]
的取值範圍是 [0, A.length]
。1 class Solution { 2 func bestRotation(_ A: [Int]) -> Int { 3 var n:Int = A.count 4 var res:Int = 0 5 var change:[Int] = [Int](repeating:0,count:n) 6 for i in 0..<n 7 { 8 change[(i - A[i] + 1 + n) % n] -= 1 9 } 10 for i in 1..<n 11 { 12 change[i] += change[i - 1] + 1 13 res = (change[i] > change[res]) ? i : res 14 } 15 return res 16 } 17 }