LeetCode453. Minimum Moves to Equal Array Elements我是這麼解答的

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) {
        int min = nums[0];
        int sum = 0;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];
            if (min > nums[i]) {
                min = nums[i];
            }
        }
        return sum - nums.size() * min;
    }
};

我當時就是這麼想的,題目意思等同於:每個數都加一後其中一個數減一,那麼要讓每個數相等,最終就會是每個數都等於最小的那個數。那麼要求最小次數就是每個數減去最小數,再求和。



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