453. Minimum Moves to Equal Array Elements(easy)
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 暴力破解(Time limited)超时不通过
思路 每次把n-1个较小的数加1,直到所有数相同
class Solution:
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#每次 n-1 个 较小的数 +1
move = 0
n = len(nums)
if n == 2:return max(nums) - min(nums)
for i in range(max(nums) - min(nums))
while(nums.count(nums[0])!=n):
maxidx = nums.index(max(nums))
for i in range(len(nums)):
if i != maxidx:nums[i] += 1
move += 1
return move
2 画图解方程,nums每的每一个数字转成一个直方柱,数字加一就相当于柱子变长,最后所有柱子高度相同变成一个矩形
矩形面积 = 红色面积 + 绿色面积,其中绿色面积 = sum(nums)
因为最后所有数字都相同 所以设最后相同的数字为k,设数组长为n,n个k,总和为 n * k,即矩形的面积
数组里最小的数字肯定是一直在加一没有间断的,所以moves = k - min(nums), moves的长度就是上图蓝色的柱子
moves轮 n-1 个数加一,所以加了 moves*(n-1),即红色面积
所以根据面积公式有:n*k = moves*(n-1) + sum(nums)
回带k = moves + min(nums),最终有:n*(moves + min(nums)) = moves*(n-1) + sum(nums)
(别忘了n = len(nums))解得 moves = sum(nums) - len(nums)* min(nums)
class Solution:
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#画图理解 n=len(),k = number attach,moves,shadow + sum = k*n->求move
#shadow = k * n
#moves = k - min(nums)
#sum(nums) + moves*(n-1)= k*n
#回带k-》sum(nums) + moves*(n-1) = (moves+min(nums)) * n 解一元一次方程
#moves = sum(nums) - n* min(nums)
return sum(nums) - len(nums)* min(nums)
3 思路2,不是很理解的一个思路,把加1看成减1,结果可以合并成思路2
total = 0
mini = min(nums)
for num in nums:
total += num - mini
return total