在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。 示例: 输入: [1,2,3] 输出: 3 解释: 只需要3次移动(注意每次移动会增加两个元素的值): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 56ms 1 class Solution { 2 func minMoves(_ nums: [Int]) -> Int { 3 var min = nums.first! 4 var sum = 0 5 for num in nums { 6 sum += num 7 if num < min { 8 min = num 9 } 10 } 11 return sum - nums.count*min 12 } 13 } 84ms 1 class Solution { 2 func minMoves(_ nums: [Int]) -> Int { 3 var minNum = Int.max 4 var sum = 0 5 for num in nums { 6 sum += num 7 minNum = min(minNum, num) 8 } 9 10 return sum - minNum * nums.count 11 } 12 } 88ms 1 class Solution { 2 func minMoves(_ nums: [Int]) -> Int { 3 let min = nums.min()! 4 return nums.reduce(0 ,{$0 + $1}) - min * nums.count 5 } 6 } 104ms 1 class Solution { 2 func minMoves(_ nums: [Int]) -> Int { 3 if nums.isEmpty { return 0 } 4 var mini = nums[0] 5 6 for num in nums { 7 mini = min(num, mini) 8 } 9 10 var res = 0 11 for num in nums { 12 res += num - mini 13 } 14 return res 15 } 16 } 116ms 1 class Solution { 2 func minMoves(_ nums: [Int]) -> Int { 3 let min = nums.min()! 4 5 return nums.reduce(0) { total, num in total + num - min } 6 } 7 }
|
请发表评论