You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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]
class Solution {
public:
int minMoves(vector<int>& nums) {
int mn = INT_MAX, res = 0;
for (int num : nums) mn = min(mn, num);
for (int num : nums) res += num - mn;
return res;
}
};
我们也可以求出数组的数字之和 sum,然后用 sum 减去最小值和数组长度的乘积,也能得到答案,注意为了避免整型溢出,将所有变量用长整型 long 来表示,参见代码如下:
解法二:
class Solution {
public:
int minMoves(vector<int>& nums) {
long mn = INT_MAX, sum = 0, res = 0;
for (long num : nums) {
mn = min(mn, num);
sum += num;
}
return sum - mn * nums.size();
}
};
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:
这道题给了我们一个长度为n的数组,说是每次可以对 n-1 个数字同时加1,问最少需要多少次这样的操作才能让数组中所有的数字相等。那么想,为了快速的缩小差距,该选择哪些数字加1呢,不难看出每次需要给除了数组最大值的所有数字加1,这样能快速的到达平衡状态。但是这道题如果老老实实的每次找出最大值,然后给其他数字加1,再判断是否平衡,思路是正确,但是 OJ 不答应。正确的解法相当的巧妙,需要换一个角度来看问题,其实给 n-1 个数字加1,效果等同于给那个未被选中的数字减1,比如数组 [1,2,3],给除去最大值的其他数字加1,变为 [2,3,3],全体减1,并不影响数字间相对差异,变为 [1,2,2],这个结果其实就是原始数组的最大值3自减1,那么问题也可能转化为,将所有数字都减小到最小值,这样难度就大大降低了,只要先找到最小值,然后累加每个数跟最小值之间的差值即可,参见代码如下:
解法一:
我们也可以求出数组的数字之和 sum,然后用 sum 减去最小值和数组长度的乘积,也能得到答案,注意为了避免整型溢出,将所有变量用长整型 long 来表示,参见代码如下:
解法二:
Github 同步地址:
#453
参考资料:
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93822/Simple-one-liners
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93815/Java-O(n)-solution.-Short.
LeetCode All in One 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: