453. Minimum Moves to Equal Array Elements --leetcode


编程练习,多多思考。

题目

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]

思路

原题的意思是对每次对 list 中 n-1 个元素加 1 ,直到 list 中元素相等的次数,可以反过来想,对 n-1 个元素加 1 ,就等于对 1 个元素减 1,这样就很容易了,原题就相当于,计算对 list 中每个元素减 1 ,直到 list 中元素相等的次数

python解法

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
move = 0
nums.sort()
for i in nums[1:]:
move += i - nums[0]
return move