-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMakeArrayZeroBySubtractingEqualAmounts.java
More file actions
51 lines (42 loc) · 1.1 KB
/
MakeArrayZeroBySubtractingEqualAmounts.java
File metadata and controls
51 lines (42 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Description: https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts
* Difficulty: Easy
*/
public class MakeArrayZeroBySubtractingEqualAmounts {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public int minimumOperationsViaSet(int[] nums) {
Set<Integer> unique = new HashSet<>();
for (int num : nums) {
if (num != 0) unique.add(num);
}
return unique.size();
}
/**
* Time complexity: O(nlog n + n)
* Space complexity: O(log n)
*/
public int minimumOperationsViaSorting(int[] nums) {
Arrays.sort(nums);
int current = 0;
int operations = 0;
int subtract = 0;
while (current < nums.length) {
int num = nums[current] - subtract;
if (num == 0) {
current++;
continue;
}
subtract += num;
operations++;
current++;
}
return operations;
}
}