LeetCode——5777. 使数组元素相等的减少操作次数(Reduction Operations to Make the Array Elements ...][中等]——分析及代码(Java)

LeetCode——5777. 使数组元素相等的减少操作次数[Reduction Operations to Make the Array Elements Equal][中等]——分析及代码[Java]

一、题目

给你一个整数数组 nums ,你的目标是令 nums 中的所有元素相等。完成一次减少操作需要遵照下面的几个步骤:

  1. 找出 nums 中的 最大 值。记这个值为 largest 并取其下标 i (下标从 0 开始计数)。如果有多个元素都是最大值,则取最小的 i 。
  2. 找出 nums 中的 下一个最大 值,这个值 严格小于 largest ,记为 nextLargest 。
  3. 将 nums[i] 减少到 nextLargest 。

返回使 nums 中的所有元素相等的操作次数。

示例 1:

输入:nums = [5,1,3]
输出:3
解释:需要 3 次操作使 nums 中的所有元素相等:
1. largest = 5 下标为 0 。nextLargest = 3 。将 nums[0] 减少到 3 。nums = [3,1,3] 。
2. largest = 3 下标为 0 。nextLargest = 1 。将 nums[0] 减少到 1 。nums = [1,1,3] 。
3. largest = 3 下标为 2 。nextLargest = 1 。将 nums[2] 减少到 1 。nums = [1,1,1] 。

示例 2:

输入:nums = [1,1,1]
输出:0
解释:nums 中的所有元素已经是相等的。

示例 3:

输入:nums = [1,1,2,2,3]
输出:4
解释:需要 4 次操作使 nums 中的所有元素相等:
1. largest = 3 下标为 4 。nextLargest = 2 。将 nums[4] 减少到 2 。nums = [1,1,2,2,2] 。
2. largest = 2 下标为 2 。nextLargest = 1 。将 nums[2] 减少到 1 。nums = [1,1,1,2,2] 。 
3. largest = 2 下标为 3 。nextLargest = 1 。将 nums[3] 减少到 1 。nums = [1,1,1,1,2] 。 
4. largest = 2 下标为 4 。nextLargest = 1 。将 nums[4] 减少到 1 。nums = [1,1,1,1,1] 。

提示:

  • 1 <= nums.length <= 5 * 10^4
  • 1 <= nums[i] <= 5 * 10^4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reduction-operations-to-make-the-array-elements-equal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、分析及代码

1. 模拟

(1)思路

对整数数组 nums 进行排序,从大到小模拟各元素的减小过程,并在过程中统计每次操作的元素个数。

(2)代码

class Solution {
    public int reductionOperations(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length, val = nums[n - 1], ans = 0;
        for (int i = n - 2; i >= 0; i--) {
            while (i >= 0 && nums[i] == val)//遍历当前与值val相同的数
                i--;
            if (i >= 0) {//当前值不是最小值
                ans += (n - i - 1);//当前值为val的元素全部减小为下一个最大值,个数为n-i-1
                val = nums[i];//改变后的最大值
            }
        }
        return ans;
    }
}

(3)结果

执行用时 :39 ms,在所有 Java 提交中击败了 100.00% 的用户;
内存消耗 :48.2 MB,在所有 Java 提交中击败了 100.00% 的用户。
(目前提交用户量不足,暂无排名)

三、其他

暂无。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值