[LeetCode]Minimum Moves to Equal Array Elements II

题目描述:

LeetCode 462. Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array's length is at most 10,000.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

题目大意:

给定非空整数数组,求使得数组中的所有元素均相等的最小移动次数,一次移动是指将某个元素加1或者减1。

你可以假设数组长度不超过10000。

解题思路:

求数组各元素与中位数差的绝对值之和

Python代码:

class Solution(object):
    def minMoves2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        median = nums[len(nums) / 2]
        return sum(abs(num - median) for num in nums)

另一种解法:

参考《编程之美》 小飞的电梯调度算法 解析

Python代码:

class Solution(object):
    def minMoves2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cnt = collections.Counter(nums)
        last, size = min(nums), len(nums)
        ans = mov = sum(nums) - last * size
        lo, hi = 0, size
        for k in sorted(cnt):
            mov += (lo - hi) * (k - last)
            hi -= cnt[k]
            lo += cnt[k]
            ans = min(ans, mov)
            last = k
        return ans

 

本文链接:http://bookshadow.com/weblog/2016/11/20/leetcode-minimum-moves-to-equal-array-elements-ii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码