LeetCode 453. Minimum Moves to Equal Array Elements
2017-07-26 16:44
399 查看
453. Minimum Moves to Equal Array Elements
Description
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]
Solution
题意即给一个n大小的数组,返回最小的更改次数(更改即+1,每次更改n-1个数),使得最终所有的数字相等。我们先设sum是最后数组的和,m是最小的更改次数,min_num是原始数组中最小的数字,x是最终的数字。
那么我们有
sum + m * (n - 1) = x * n并且有
x = minNum + m(贪心的思想) 联立可以解出
sum - minNum * n = m代码如下
int minMoves(int* nums, int numsSize) { if (numsSize == 0) return 0; int min_num = nums[0],sum = nums[0]; for (int i = 1;i < numsSize;i++) { if (nums[i] < min_num) min_num = nums[i]; sum += nums[i]; } return sum - numsSize * min_num; }
相关文章推荐
- [Leetcode] 453. Minimum Moves to Equal Array Elements 解题报告
- [leetcode]453. Minimum Moves to Equal Array Elements
- LeetCode 453. Minimum Moves to Equal Array Elements
- LeetCode 453. Minimum Moves to Equal Array Elements
- 【Leetcode】453. Minimum Moves to Equal Array Elements
- leetcode:453. Minimum Moves to Equal Array Elements
- leetcode 453. Minimum Moves to Equal Array Elements
- 【C语言】 leetcode 453. Minimum Moves to Equal Array Elements
- [leetcode]: 453. Minimum Moves to Equal Array Elements
- leetcode 453. Minimum Moves to Equal Array Elements(C语言,又是一招出奇制胜)46
- [leetcode] 453. Minimum Moves to Equal Array Elements 解题报告
- leetcode 453. Minimum Moves to Equal Array Elements
- LeetCode-453. Minimum Moves to Equal Array Elements
- Leetcode——453. Minimum Moves to Equal Array Elements
- 【LeetCode】 453. Minimum Moves to Equal Array Elements
- 【leetcode】【Easy】【453. Minimum Moves to Equal Array Elements】【math】
- Leetcode 453. Minimum Moves to Equal Array Elements
- LeetCode 453. Minimum Moves to Equal Array Elements
- leetcode453. Minimum Moves to Equal Array Elements
- [LeetCode]453. Minimum Moves to Equal Array Elements(最少移动直到数组元素相等)