leetcode 453. Minimum Moves to Equal Array Elements ( Python )

559 阅读21分钟

描述

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-1 个数字加一,直到所有的数字都相等,计算总共操作了多少步,其实转换一下思维,要求结果,可以每次对数组中的最大值减一,一直减到所有数字相等,操作的次数就是结果值,时间复杂度为 O(1),空间复杂度为 O(1)。

解答

class Solution(object):
def minMoves(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    return sum(nums)-min(nums)*len(nums)                    	      
		

运行结果

Runtime: 216 ms, faster than 98.21% of Python online submissions for Minimum Moves to Equal Array Elements.
Memory Usage: 12.9 MB, less than 57.89% of Python online submissions for Minimum Moves to Equal Array Elements.

解析

根据题意,可以通过观察发现规律

长度 次数
 1  0
 2  1
 3  3
 4  6
 5  10
 6  15
 7  21
 8  28
 9  36
 10 45
 ...

第 n 次的次数是第 n-1 次的次数加 n-1,时间复杂度为 O(N),空间复杂度为 O(1)。

解答

class Solution:
    def minMoves(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        res = 0
        for num in nums:
            res += num - nums[0]
        return res

                   	      
		

运行结果

Runtime: 260 ms, faster than 14.85% of Python online submissions for Minimum Moves to Equal Array Elements.
Memory Usage: 12.9 MB, less than 71.05% of Python online submissions for Minimum Moves to Equal Array Elements.

每日格言:人生最大遗憾莫过于错误坚持和轻易放弃

请作者吃狗果冻 支付宝

支付宝

微信

微信