-
Notifications
You must be signed in to change notification settings - Fork 0
/
539. Minimum Time Difference
57 lines (47 loc) · 1.62 KB
/
539. Minimum Time Difference
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
52
53
54
55
56
57
import java.util.*;
class Solution {
public int findMinDifference(List<String> timePoints) {
final int TOTAL_MINUTES = 24 * 60;
boolean[] seen = new boolean[TOTAL_MINUTES];
int count = 0;
// Convert times to minutes and place them into buckets
for (String time : timePoints) {
int minutes = convertToMinutes(time);
if (seen[minutes]) {
return 0; // Duplicate times result in zero difference
}
seen[minutes] = true;
count++;
}
if (count == 1) {
return 0; // Only one time point, no meaningful difference
}
// Compute minimum difference between adjacent buckets
int prev = -1;
int minDiff = Integer.MAX_VALUE;
int firstTime = -1;
int lastTime = -1;
for (int i = 0; i < TOTAL_MINUTES; i++) {
if (seen[i]) {
if (prev != -1) {
minDiff = Math.min(minDiff, i - prev);
}
prev = i;
if (firstTime == -1) {
firstTime = i;
}
lastTime = i;
}
}
// Check the difference between the last and the first bucket (wrap-around)
if (firstTime != -1 && lastTime != -1) {
minDiff = Math.min(minDiff, TOTAL_MINUTES - lastTime + firstTime);
}
return minDiff;
}
private int convertToMinutes(String time) {
int h = Integer.parseInt(time.substring(0, 2));
int m = Integer.parseInt(time.substring(3));
return h * 60 + m;
}
}