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

請做者吃狗果凍
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索