LCP 50. 宝石补给
一、题目
每位勇者初始都拥有一些能量宝石, gem[i]
表示第 i
位勇者的宝石数量。现在这些勇者们进行了一系列的赠送,operations[j] = [x, y]
表示在第 j
次的赠送中 第 x
位勇者将自己一半的宝石(需向下取整)赠送给第 y
位勇者。
在完成所有的赠送后,请找到拥有最多宝石的勇者和拥有最少宝石的勇者,并返回他们二者的宝石数量之差。
二、思路
按照题目描述,首先遍历 operations,计算出赠予的宝石数量,然后直接在 gem 数组上对两位勇者的宝石数增减相应的宝石数量。然后遍历 gem 数组,计算出宝石数量最大值和最小值,计算差值后返回。
三、代码
class Solution { public: int giveGem(vector<int>& gem, vector<vector<int>>& operations) { for (auto &operation : operations) { int x = operation[0], y = operation[1]; int number = gem[x] / 2; gem[x] -= number; gem[y] += number; } int mn = *min_element(gem.begin(), gem.end()); int mx = *max_element(gem.begin(), gem.end()); return mx - mn; } };
四、分析
复杂度分析
-
时间复杂度:O(m+n),其中 m 是数组 operations 的长度,n 是数组 gem 的长度。我们需要遍历两个数组各一次。
-
空间复杂度:O(1),我们仅使用常数空间。