【leetcode】453. Minimum Moves to Equal Array Elements【E】

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]

Subscribe to see which companies asked this question

這個問題,看tag是個math

然後簡單分析,其實就是可以這樣做

把數組排序,然後每個元素減去最小的元素,再把剩下的結果加起來,就是答案了

我是終於理解人們爲什麼要一行代碼解決問題了,因爲有成就感啊!!哈哈哈



class Solution(object):
    def minMoves(self, nums):
        return sum(nums) - min(nums)*(len(nums))



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章