本文主要是介绍LeetCode 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]
思路:
因为sum+m*(len-1)=x*len,min+m=x,sum-num*len=m,所以就是需要求出最小值,结果就是结果 返回sum-num*len
代码:
class Solution {
public:int minMoves(vector<int>& nums) {int sum=0;int min=nums[0];//min的初始值为数组第一个元素int len=nums.size();for(int i=0;i<len;++i){min=nums[i]<min?nums[i]:min;//求数组中最小的元素sum+=nums[i];//求和}return sum-min*len;//根据思路说明返回结果}
};
**输出结果:**53ms
这篇关于LeetCode 453. Minimum Moves to Equal Array Elements的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!