欢迎各位勇者来到力扣新手村,在开始试炼之前,请各位勇者先进行「宝石补给」。

每位勇者初始都拥有一些能量宝石, gem[i] 表示第 i 位勇者的宝石数量。现在这些勇者们进行了一系列的赠送,operations[j] = [x, y] 表示在第 j 次的赠送中 第 x 位勇者将自己一半的宝石(需向下取整)赠送给第 y 位勇者。

在完成所有的赠送后,请找到拥有最多宝石的勇者和拥有最少宝石的勇者,并返回他们二者的宝石数量之差

注意:

  • 赠送将按顺序逐步进行。

示例 1:

示例 2:

示例 3:

提示:

  • 2 <= gem.length <= 10^3
  • 0 <= gem[i] <= 10^3
  • 0 <= operations.length <= 10^4
  • operations[i].length == 2
  • 0 <= operations[i][0], operations[i][1] < gem.length

解法 模拟

按照题目描述,首先遍历 o p e r a t i o n s operations operations ,计算出赠予的宝石数量,然后直接在 g e m gem gem 数组上对两位勇者的宝石数增减相应的宝石数量。然后遍历 g e m 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 ) O(m+n) O(m+n) ,其中 m m m 是数组 o p e r a t i o n s operations operations 的长度, n n n 是数组 g e m gem gem 的长度。我们需要遍历两个数组各一次。
  • 空间复杂度: O ( 1 ) O(1) O(1) ,我们仅使用常数空间。
09-17 01:56