-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDistributeCandies.java
More file actions
47 lines (39 loc) · 1.08 KB
/
DistributeCandies.java
File metadata and controls
47 lines (39 loc) · 1.08 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
package array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Description: https://leetcode.com/problems/distribute-candies
* Difficulty: Easy
*/
public class DistributeCandies {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public int distributeCandiesViaSet(int[] candyType) {
Set<Integer> eaten = new HashSet<>();
int candiesLeft = candyType.length / 2;
for (int candy : candyType) {
if (eaten.add(candy)) {
if (--candiesLeft == 0) break;
}
}
return eaten.size();
}
/**
* Time complexity: O(nlog n)
* Space complexity: O(log n)
*/
public int distributeCandiesViaSorting(int[] candyType) {
Arrays.sort(candyType);
int candiesLeft = candyType.length / 2;
int eaten = 0;
for (int i = 0; i < candyType.length; i++) {
if (i > 0 && candyType[i - 1] == candyType[i]) continue;
eaten++;
if (--candiesLeft == 0) break;
}
return eaten;
}
}