LeetCode #453 最小操作次数使数组元素相等
基本思路
每次让数组的n-1个元素加1——等价于——每次让一个元素减1;
把所有数加到相同的最大值 ——等价于——把所有的数捡到最小值;
因此最小操作次数 = 数组所有元素之和 - ( 数组长度 * 最小值);
标程
1 class Solution { 2 public: 3 int minMoves(vector<int>& nums) { 4 int min_num = *min_element(nums.begin(),nums.end()); 5 int res = 0; 6 for(int num : nums){ 7 res += num; 8 } 9 res -= nums.size() * min_num; 10 return res; 11 } 12 };
时间复杂度
O(N)

浙公网安备 33010602011771号