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

描述

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.php

Example:ios

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.
复制代码

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

请做者吃狗果冻
支付宝

支付宝

微信

微信
相关文章
相关标签/搜索