【leetcode】462. Minimum Moves to Equal Array Elements II【M】

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章