leetcode-Minimum Moves to Equal Array Elements

Question:

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

Example:

Input:
[1,2,3]

Output:
3

Explanation:
Only three moves are needed (remember each move increments two elements):

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

Solution:

class Solution {
public:
    int minMoves(vector<int>& nums) {
        if(nums.empty() || nums.size() == 1){
            return 0;
        }
        int len = nums.size();
        //sort(nums.begin(),nums.end());
        int min = nums[0];
        for(int i = 0 ; i < len ;i++){
            if(min>nums[i]){
                min = nums[i];
            }
        }
        int res = 0;
        for(int i = 0 ; i < len ;i++){
            res+=nums[i]-min;
        }
        return res;
    }
};

總結:
雖然難易程度是easy,不過感覺還是挺繞的,關鍵是理解了moves = 每一個數與最小數之差的和。

每一次給除x之外的其他n-1個數加一之後,x就不用再計算了,該次moves=x-min,並且其他數和最小數的差不變,總共執行n-1次,每一次的moves=x-min;所以總數就是每一個數-min之和。

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