1. 程式人生 > >leetcode 453. 最小移動次數使陣列元素相等(Minimum Moves to Equal Array Elements)

leetcode 453. 最小移動次數使陣列元素相等(Minimum Moves to Equal Array Elements)

給定一個長度為 n 的非空整數陣列,找到讓陣列所有元素相等的最小移動次數。每次移動可以使 n - 1 個元素增加 1。

示例:

輸入:
[1,2,3]

輸出:
3

解釋:
只需要3次移動(注意每次移動會增加兩個元素的值):

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

逆向思考,讓n-1個數+1不就等價於讓一個數-1嗎,那不就是把其他數砍到和最小數一樣小不就都相等了嗎,這個砍了幾次呢???

class Solution {
    public int minMoves(int[] nums) {
        int sum=0;
        int min = Integer.MAX_VALUE;
        for(int x:nums){
            sum+=x;
            if(x<min)
                min = x;
        }
        return sum - min*nums.length;
    }
}

在任何移動之前,讓我們將sum定義為所有數字的總和; minNum作為列表中的最小數字; n是列表的長度;

之後,比如m移動,我們得到所有數字為x,我們將得到以下等式

 sum + m * (n - 1) = x * n

實際上,

x = minNum + m

這部分可能有點混亂,但@shijungg解釋得很好。讓我再解釋一下。它來自兩個觀察結果:

  1. 最小數量將始終為最小值,直到達到最終數字,因為每次移動,其他數字(除了最大值)也會增加;
  2. 從上面我們可以得到,最小數量將在每一步中遞增。所以,如果最終的數字是x,那麼minNum +移動;

最後,我們會得到

  sum - minNum * n = m

這只是一個數學計算。

let's define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list;

After, say m moves, we get all the numbers as x , and we will get the following equation

 sum + m * (n - 1) = x * n

and actually,

  x = minNum + m

This part may be a little confusing, but @shijungg explained very well. let me explain a little again. it comes from two observations:

  1. the minum number will always be minum until it reachs the final number, because every move, other numbers (besides the max) will be increamented too;
  2. from above, we can get, the minum number will be incremented in every move. So, if the final number is x, it would be minNum + moves;

and finally, we will get

  sum - minNum * n = m

This is just a math calculation.

解決方案沒有錯,但推理不正確:總有一個解決方案並不明顯; 您提供的解決方案都不是最佳的。

有效地將1新增到n - 1個元素相當於從1個元素中減去1。因此,問題轉換為:每個步驟允許從1個元素中刪除1,並且您的目標是使所有元素相等。

去除後,總和為minNum * n,因此所需步數為sum - minNum * n。

The solution is not wrong, but the reasoning is not right: it is not obvious that there is always a solution; neither the solution you provide is optimal. Adding 1s to n - 1 elements effectively is equivalent to subtracting 1 from 1 element. Therefore the question is transformed to: you are allowed to remove 1 from 1 element each steps, and your goal is to make all element equal. After the removal, total sum is minNum * n, hence the number of step needed is sum - minNum * n.