题目:
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 非空的数组,找到最小的移动次数使得所有数组中元素大小相等,每移动一次,使 n - 1 个元素增加1。
思路:
把这道题看成一道数学题去解决,解析过程参见如下,摘自leetCode中的解答。
let's define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list;
After, say m moves, we get all the numbers as x , and we will get the following equation
sum + m * (n - 1) = x * n
and actually,
x = minNum + m
This part may be a little confusing, but @shijungg explained very well. let me explain a little again. it comes from two observations:
- the minum number will always be minum until it reachs the final number, because every move, other numbers (besides the max) will be increamented too;
- from above, we can get, the minum number will be incremented in every move. So, if the final number is x, it would be minNum + moves;
and finally, we will get
sum - minNum * n = m
This is just a math calculation.
C++代码(Visual Studio 2017):
#include "stdafx.h" #include <iostream> #include <vector> #include<algorithm> using namespace std; class Solution { public: int minMoves(vector<int>& nums) { int res=0; int sum = 0; int m = *min_element(nums.begin(),nums.end()); for (int i = 0; i < nums.size(); i++) sum += nums[i]; //cout << sum; return sum- m*nums.size(); } }; int main() { Solution s; vector<int> nums = { 1,2,3 }; int result; result = s.minMoves(nums); cout << result; return 0; }