标签:etc tco element tps lock view code res leetcode
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 n = nums.size(); int sum = 0; sort(nums.begin(), nums.end()); for (int num : nums) sum += num; return sum - nums[0] * n; } }; // 82 ms
如果要使所有的数字都相等,则每个值到最大值之间的差都应该被计算为执行的次数。
class Solution { public: int minMoves(vector<int>& nums) { sort(nums.begin(), nums.end()); int res = 0; for (int i = 0; i != nums.size(); i++) res += (nums[i] - nums[0]); return res; } }; // 76 ms
[LeetCode] Minimum Moves to Equal Array Elements
标签:etc tco element tps lock view code res leetcode
原文地址:http://www.cnblogs.com/immjc/p/7163247.html