Python 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]
[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操作,最终达到数组中的n个数相等的状态,求一共进行了多少次操作。
博客看到的很好的思想:
我感觉我在想算法问题的时候,有种弊端,就是总是一步一步的去演算,而不是结合结果,针对目标将整个过程简化为一个通项公式,这样对于整个过程的求解就是一个公式的问题了
思路:目标:最终每个数一样 过程:每次移动n-1个数,每个数加1
假设数组为 a1,a2,a3,……,an,不妨假设a1<a2<a3<……<an。首先,将a1移到与a2相等,需要移动a2-a1步,序列变成a2,a2,a3+a2-a1,……,an+a2-a1。继续将a2移到与a3相等,需要移动 (a3+a2-a1)- a2 = a3-a1步,此时,序列变成a3+a2-a1,a3+a2-a1,a3+a2-a1,……an+a2-a1+a3-a1。如此往复下去,最后,将前n-1个数移动an-a1步,即将所有数字变成相等。即每一次移动,都需要移当前数字与最小数字相减的步数。
故总的移动步数为 a2-a1 + a3-a1 + …… + an-a1。其中,a1为数组中的最小的数。
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count=0
minx=min(nums)
for x in nums:
count+=(x-minx)
return count