-
Notifications
You must be signed in to change notification settings - Fork 1
/
mtd.go
129 lines (120 loc) · 2.4 KB
/
mtd.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package mtd
import (
"math"
"sort"
"strconv"
"strings"
"github.com/catorpilor/leetcode/utils"
)
func minDiff(tps []string) int {
return iterator(tps)
}
// iterator time complexity is O(nlgn), space complexity is O(N)
func iterator(tps []string) int {
hset := map[string]int{
"00": 0,
"01": 60,
"02": 120,
"03": 180,
"04": 240,
"05": 300,
"06": 360,
"07": 420,
"08": 480,
"09": 540,
"10": 600,
"11": 660,
"12": 720,
"13": 780,
"14": 840,
"15": 900,
"16": 960,
"17": 1020,
"18": 1080,
"19": 1140,
"20": 1200,
"21": 1260,
"22": 1320,
"23": 1380,
}
sort.Slice(tps, func(i, j int) bool { return tps[i] < tps[j] })
n := len(tps)
ret := diffWithHset(hset, tps[0], tps[n-1])
for i := 0; i < n-1; i++ {
ret = utils.Min(ret, diffWithHset(hset, tps[i], tps[i+1]))
}
return ret
}
func diffWithHset(hset map[string]int, left, right string) int {
f := func(c rune) bool {
return c == ':'
}
lefts := strings.FieldsFunc(left, f)
rights := strings.FieldsFunc(right, f)
rm, _ := strconv.Atoi(rights[1])
rt := hset[rights[0]] + rm
lm, _ := strconv.Atoi(lefts[1])
lt := hset[lefts[0]] + lm
if rights[0] > "12" && lefts[0] < "06" {
lt += 24 * 60
}
return utils.Abs(rt - lt)
}
func simpler(tps []string) int {
sort.Slice(tps, func(i, j int) bool { return tps[i] < tps[j] })
n := len(tps)
res := math.MaxInt32
var j int
for i := 0; i < n; i++ {
j = i - 1
if i == 0 {
j = n - 1
}
dif := utils.Abs(diffs(tps[j], tps[i]))
// 1400-dif for cases ["00:00", "23:59"]
dif = utils.Min(dif, 1440-dif)
if dif < res {
res = dif
}
}
return res
}
func diffs(l, r string) int {
hl, _ := strconv.Atoi(l[:2])
ml, _ := strconv.Atoi(l[3:])
hr, _ := strconv.Atoi(r[:2])
mr, _ := strconv.Atoi(r[3:])
return (hr-hl)*60 + (mr - ml)
}
// bucket use bucket sort, time complexity is O(N), space complexity is O(1)
func bucket(tps []string) int {
bks := make([]bool, 1440)
for _, s := range tps {
h, _ := strconv.Atoi(s[:2])
m, _ := strconv.Atoi(s[3:])
if bks[h*60+m] {
// there are duplicates
return 0
}
bks[h*60+m] = true
}
prev, last, first, res := 0, math.MinInt32, math.MaxInt32, math.MaxInt32
for i := 0; i < 1440; i++ {
if bks[i] {
if first != math.MaxInt32 {
if res > i-prev {
res = i - prev
}
}
if first > i {
first = i
}
if last < i {
last = i
}
prev = i
}
}
res = utils.Min(res, 1440+first-last)
return res
}