LeetCode Minimum Moves to Equal Array Elements

LeetCode 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]

给定一个长度为n数组,每次操作是把其中n-1个数加1,问需要多少次操作才能使数组中的所有元素都相等。 很有意思的数学题。常规思路是,每次找出数组中的最大数,然后对剩下的n-1个数加1,如此循环直到所有元素相等。但是这种解法每次操作都需要O(n)的复杂度,肯定会TLE。 另一个思路,对除最大数之外的所有数加1,相当于其他数不变,把最大数减1。所以可以先找到数组中的最小数,然后累加数组中各元素与最小值之差即可。 代码如下: [cpp] class Solution { public: int minMoves(vector<int>& nums) { int m = INT_MAX, ans = 0; for (const int& i : nums)m = min(m, i); for (const int& i : nums)ans += i – m; return ans; } }; [/cpp] 本代码提交AC,用时56MS。]]>

1 thought on “LeetCode Minimum Moves to Equal Array Elements

  1. Pingback: LeetCode Minimum Moves to Equal Array Elements II | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *