为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode453. 最小移动次数使数组元素相等 | Minimum Moves to Equal Array Elements

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9790914.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新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 }

 

posted @ 2018-10-15 14:43  为敢技术  阅读(288)  评论(0编辑  收藏  举报