[Swift]LeetCode798. 得分最高的最小轮调 | Smallest Rotation w
?Given an array? For example,if we have? 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,0] Output: 3 Explanation: Scores for each K are listed below: K = 0,A = [2,0],score 2 K = 1,A = [3,2],score 3 K = 2,A = [1,3],score 3 K = 3,A = [4,1],score 4 K = 4,A = [0,4],score 3 So we should choose K = 3,which has the highest score.? Example 2: Input: [1,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:
给定一个数组? 例如,如果数组为? 在所有可能的轮调中,返回我们所能得到的最高分数对应的轮调索引 K。如果有多个答案,返回满足条件的最小的索引 K。 示例 1: 输入:[2,0] 输出:3 解释: 下面列出了每个 K 的得分: K = 0,score 3 所以我们应当选择?K = 3,得分最高。? 示例 2: 输入:[1,4] 输出:0 解释: A 无论怎么变化总是有 3 分。 所以我们将选择最小的 K,即 0。 提示:
Runtime:?196 ms
Memory Usage:?18.9 MB
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |