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]
Subscribe to see which companies asked this question
刚开始想的是,那就让所有数都变成中位数,正如所有人都尝试过的那样,错了
甚至想到了最小二乘法和线性回归方程,不过太麻烦了
那应该怎么弄呢,看了discuss,发现应该是中位数,那是为什么呢?
没听说中位数也没这样的性质啊、
然后看到了这样一个code,就明白了
while(i < j){
count += nums[j]-nums[i];
i++;
j--;
}
就是排序之后,从两边往中间走,最大和最小之间的差距,是一定要填补上的,不管+1 还是 -1
这样,走到中间,那就是中位数了
妙
class Solution(object):
def minMoves2(self, nums):
nums.sort()
t = nums[len(nums)/2]
res= 0
for i in nums:
res += abs(i - t)
return res