LeetCode 2357. Make Array Zero by Subtracting Equal Amounts

You are given a non-negative integer array nums. In one operation, you must:

  • Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
  • Subtract x from every positive element in nums.

Return the minimum number of operations to make every element in nums equal to 0.

Example 1:

Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].

Example 2:

Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

这题不告诉我是pq的题,根本不会想到还可以用pq来做啊?

刚开始直接写了个sort的方法,然后双重while loop来用最小的非0数减每个数。注意数组下标的范围判断。

class Solution {
    public int minimumOperations(int[] nums) {
        Arrays.sort(nums);
        int result = 0;
        int index = 0;
        while (index < nums.length) {
            while (nums[index] == 0) {
                index++;
                if (index == nums.length) {
                    return result;
                }
            }
            int x = nums[index];
            for (int i = 0; i < nums.length; i++) {
                nums[i] -= x;
            }
            index++;
            result++;
        }
        return result;
    }
}

然后看了答案……发现最机智的做法既不需要sort也不需要pq……因为相同的数字永远都是相同的,直接某次一减就同时都减掉了。不同的数字永远都是不同的。所以问题就可以简化成,计算不同的非0数字的个数……实在是不知道是什么样的大天才才能想出这种方法,我自己这么想都不怎么能想得通……

class Solution {
    public int minimumOperations(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int i : nums) {
            if (i > 0) {
                set.add(i);
            }
        }
        return set.size();
    }
}

更牛逼的,直接stream一行解决。但是提交以后发现这个方法比我最开始写的还慢……

class Solution {
    public int minimumOperations(int[] nums) {
        return (int)Arrays.stream(nums).filter(a -> a > 0).distinct().count();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值