leetcode-2357-easy

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

思路一:排序后模拟求解

public int minimumOperations(int[] nums) {
        Arrays.sort(nums);

        int count = 0;
        for (int i = 0; i < nums.length; i++) {
        int val = nums[i];
        if (val == 0) continue;
        for (int j = i; j < nums.length; j++) {
        nums[j] -= val;
        }
        count++;
        }

        return count;
}

思路二:从思路一中我们可以把排序后的数组想象成向上递增的楼梯,每次下降一台阶,想要把楼梯全部变成水平,只要统计错落的楼梯有多少,即统计大于0的数字有多少种

public int minimumOperations(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for(int i = 0; i<nums.length; i++){
    if(nums[i] != 0){
    set.add(nums[i]);
    }
    }
    return set.size();
}
posted @ 2022-10-25 21:44  iyiluo  阅读(31)  评论(0)    收藏  举报