1231. 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.

您在真實的面試中是否遇到過這個題?  

樣例

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]

最開始我很笨拙的一個一個加,最後發現,然後就超時了。

然後參考了大佬的微博,http://www.cnblogs.com/grandyang/p/6053827.html

發現思路這麼簡單。。。

class Solution {
public:
    /**
     * @param nums: an array
     * @return: the minimum number of moves required to make all array elements equal
     */
    int minMoves(vector<int> &nums) {
        // Write your code here
        int mn = INT_MAX, res = 0;
        for (int num : nums) mn = min(mn, num);
        for (int num : nums) res += num - mn;
        return res;
    }
};

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