letecode [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]

题目大意

  给定非空数组,每次n-1个元素值加1,直到所有元素值相等,求最少移动次数。

理  解:

  看的别人的解法,逆向思维,其余n-1个元素加1,求相当于被选中的元素减1,即求所有元素与最小元素差值之和为最少移动次数。

代 码 C++:

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

运行结果:

  执行用时 :56 ms, 在所有 C++ 提交中击败了80.44%的用户

  内存消耗 :10.8 MB, 在所有 C++ 提交中击败了85.59%的用户
posted @ 2019-07-01 09:12  lpomeloz  阅读(130)  评论(0编辑  收藏  举报