【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]

题意:

用最小的操作使数组中所有的值相等。

思路:

排序,找出数组中所有的值和索引中间位的插值的绝对值的和

 

这个题是用Python写的,这次见识Python的高效了,

1 class Solution(object):
2     def minMoves2(self, nums):
3         """
4         :type nums: List[int]
5         :rtype: int
6         """
7         nums.sort()
8         mid=nums[len(nums)/2]
9         return sum(abs(mid-num) for num in nums)

 

posted @ 2016-12-10 21:28  wilderness  阅读(222)  评论(0)    收藏  举报