LeetCode 453 Minimum Moves to Equal Array Elements

来源:互联网 发布:百度seo规则 编辑:程序博客网 时间:2024/06/17 12:21

题目:

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)个数一次加一,要求我们计算最少需要进行多少步骤才能让所有的数都相等。

这个题绕了个弯子,假如说把(n-1)个数都加一,从达到所有数相等的目的来看,也就说相当于把剩余那一个没有加一的数(相对)减一,达到的目标是所有的数都相等,因为只能进行减一操作,所以我们只需要找出整个数组中的最小值,然后把其他所有数到这个数的步数求和即可。

类似于等价代换的思想,转个弯就好了。

代码如下:

class Solution {public:    int minMoves(vector<int>& nums) {        long long ans = 0, Min = 0xffffffff;        for (long long i : nums)             Min = (Min > i) ? i : Min;        for (long long i : nums)             ans += i - Min;        return ans;    }};
因为最后是求和的结果,可能会超出int的外围,所以直接采用long long的形式。



原创粉丝点击