LeetCode No.453 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]

===================================================================

題目鏈接:https://leetcode.com/problems/minimum-moves-to-equal-array-elements/

題目大意:給定一個數組,每次給數組中n-1個元素加1,直到所有元素值相等,求最少需要多少步。

思路:給n-1個元素加1,實際上就是給多出來的那個元素減1,所以原來題目可以轉化爲:每次給數組中的一個元素減1,直到所有元素值相等,求最少需要多少步。

注意點:sum可能超出int範圍。

參考代碼:

class Solution {
public:
    int minMoves(vector<int>& nums) {
        long long n = nums.size() ;
        if ( n <= 1 )
            return 0 ;
        long long sum = nums[0] ;
        int miner = nums[0] ;
        for ( int i = 1 ; i < n ; i ++ )
        {
            sum += nums[i] ;
            miner = min ( miner , nums[i] ) ;
        }
        return sum - n * miner ;
    }
};


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