You are given a non-negative integer array nums
. In one operation, you must:
- Choose a positive integer
x
such thatx
is less than or equal to the smallest non-zero element innums
. - Subtract
x
from every positive element innums
.
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();
}
}