算法的重要性,我就不多說了吧,想去大廠,就必須要經過基礎知識和業務邏輯面試+算法面試。是以,為了提高大家的算法能力,後續每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做 最小操作次數使數組元素相等,我們先來看題面:
https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements/
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1 elements of the array by 1.
給你一個長度為 n 的整數數組,每次操作将會使 n - 1 個元素增加 1 。傳回讓數組所有元素相等的最小操作次數。
示例
示例 1:
輸入:nums = [1,2,3]
輸出:3
解釋:
隻需要3次操作(注意每次操作會增加兩個元素的值):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
示例 2:
輸入:nums = [1,1,1]
輸出:0
複制
解題
https://blog.csdn.net/qq_45260619/article/details/113715613
我們需要先對數組進行排序,這樣可以找到數組中最大值和最小值m a x 和 m i n max和minmax和min,令 d i f = m a x − m i n dif = max - mindif=max−min,意思是:我們對除了最大值以外的數全部加上dif,這樣又可以産生新的最大值和最小值,我們隻需要重複進行操作即可。
那麼我們怎樣迅速找到最大值和最小值呢?
我們進行操作之前的數組是:[ a 1 , a 2 , a 3... , a n ] [a1,a2 ,a3...,an][a1,a2,a3...,an],此時是有序的,那麼我們對除了 a n anan 的所有數加上 d i f difdif 之後,那麼 a 1 > = a n , a 2 > = a n ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ a ( n − 1 ) > = a n a1 >= an , a2 >= an ······ a(n-1) >= ana1>=an,a2>=an⋅⋅⋅⋅⋅⋅a(n−1)>=an,那麼此時數組中的最大值變為了 a ( n − 1 ) a(n-1)a(n−1) , 最小值仍然是 a 0 a0a0 , 那麼再次循環,最大值變為了 a ( n − 2 ) a(n-2)a(n−2) ,最小值仍然是 a 0 a0a0 ,如此循環即可找到答案。
class Solution {
public:
int minMoves(vector<int>& nums) {
sort(nums.begin() , nums.end());
int res = 0;
for(int i = nums.size() - 1; i > 0; i--)
{
res += nums[i] - nums[0];
}
return res;
}
};
複制
上期推文:
LeetCode1-440題彙總,希望對你有點幫助!
LeetCode刷題實戰441:排列硬币
LeetCode刷題實戰442:數組中重複的資料
LeetCode刷題實戰443:壓縮字元串
LeetCode刷題實戰444:序列重建
LeetCode刷題實戰445:兩數相加 II
LeetCode刷題實戰446:等差數列劃分 II - 子序列
LeetCode刷題實戰447:回旋镖的數量
LeetCode刷題實戰448:找到所有數組中消失的數字
LeetCode刷題實戰449:序列化和反序列化二叉搜尋樹
LeetCode刷題實戰450:删除二叉搜尋樹中的節點
LeetCode刷題實戰451:根據字元出現頻率排序
LeetCode刷題實戰452:用最少數量的箭引爆氣球