【python3】leetcode 453. Minimum Moves to Equal Array Elements(easy)

120 篇文章 0 订阅

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

every move means select #n-1 numbers plus 1, which equals to select #1 number minus 1.hence, just every number reduce to the minimum number. 

 

        total = 0
        mini = min(nums)
        
        for num in nums:
            total += num - mini
        
        return total

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值