leetcode_453. Minimum Moves to Equal Array Elements 移动最小步数使数组中各数字相等

题目:

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。问,需要最少移动多少步,可以使数组中各数字最后相等。


代码:

class Solution(object):
    def minMoves(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        n = len(nums)
        if n < 2 :
            return 0
        else :
            min_num = min(nums)        #找数组中最小的数
            
            res = 0                  #记录移动的步数
            
            for i in range(n) :
                res += nums[i]-min_num              #每个数字减去最小数字的和,即为最终的需要移动的最小步数
            
            return res


笔记:

思路:

假设数组为 a1,a2,a3,……,an,不妨假设a1

故总的移动步数为 a2-a1 + a3-a1 + …… + an-a1。其中,a1为数组中的最小的数。


你可能感兴趣的:(leetcode_453. Minimum Moves to Equal Array Elements 移动最小步数使数组中各数字相等)