LeetCode_453. Minimum Moves to Equal Array Elements

来源:互联网 发布:linux lcd驱动程序 编辑:程序博客网 时间:2024/05/16 10:52

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:3Explanation:Only three moves are needed (remember each move increments two elements):[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

题意理解:
长度n的非空数组,每次对(n-1)个元素执行加1操作,直到最后数组中的每个元素相等,求操作的最小次数。

思路:
refernce:
http://blog.csdn.net/shihongliang1993/article/details/53070758
每次加1的n-1个元素必定是数组中最小的n-1个元素;
把最小的n-1个元素都加1,相当于所有元素都加1的基础上,最大的元素减1,因为题目最后要求所有元素值相等即可,那么所有元素的加1操作可以忽略,即每次“移动”操作等价于将最大的元素减1,直至所有元素均等于原始数组中的最小值。
每个元素需做(nums[i]-min)次减法。
共需
(nums[0]-min) + (nums[1]-min) + (nums[2]-min) + … + (nums[len-1]-min)
= sum(nums) - min*len次操作。

class Solution {public:    int minMoves(vector<int>& nums) {        int sum=0;        int min=nums[0];        for (int i=0; i<nums.size(); i++)        {            sum += nums[i];            if (min>nums[i])            {                min = nums[i];            }        }        return sum-min*nums.size();    }};
0 0
原创粉丝点击