[Swift]LeetCode453. 最小移動次數使數組元素相等 | Minimum Moves to Equal Array Elements

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-grendtyr-hk.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.git

Example:github

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 }

84msui

 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 }

88msspa

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 }

104mscode

 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 }

116mshtm

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 }
相關文章
相關標籤/搜索