您的位置:首页 > 编程语言 > Python开发

【LeetCode】462. Minimum Moves to Equal Array Elements II 解题报告(Python)

2018-03-04 17:00 671 查看

【LeetCode】462. Minimum Moves to Equal Array Elements II 解题报告(Python)

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/

题目描述:

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.

解题方法

方法一:

题意已经明确了,把数字调整相等的最小步数,一定是把大数变小,把小数变大,最后都达到其
中位数
(注意不是均值)。最小化全部/平均距离是中位数的一个显著的性质。

Minimizing the total/average distance is just a prominent property of a median.

可以举例来看:

对于 [1, 5, 6],其均值是4, 中位数是5.

如果把所有的数字都移动到4,需要sum([3,1,2])=6步;

如果把所有的数字都移动到5,需要sum([4,0,1])=5步。


我的理解是,移动到均值容易受到极端值的影响,而移动到中位数则不存在这个问题。具体的数学证明我不会。。当做定理记住好了。

代码:

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


方法二:

同样使用排序去做。新学会了
~i
运算。即求反。python支持负数索引,所以这个运算符很实用啊。

The ~ operator is the same as in C++, so 0, 1, 2, … get turned into -1, -2, -3, …. But C++ doesn’t support negative indexing. In Python, index -1 means the last element, index -2 means the next-to-last element, etc.

代码:

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


日期

2018 年 3 月 4 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: