-
Notifications
You must be signed in to change notification settings - Fork 0
/
map_sum_pairs.go
68 lines (56 loc) · 1.11 KB
/
map_sum_pairs.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
package main
import (
"sort"
"strings"
)
type Item struct {
key string
value int
}
type Items []Item
func (items Items) Len() int {
return len(items)
}
func (items Items) Less(i, j int) bool {
if items[i].key < items[j].key {
return true
}
return false
}
func (items Items) Swap(i, j int) {
items[i], items[j] = items[j], items[i]
}
type MapSum struct {
items Items
}
func Constructor() MapSum {
return MapSum{Items{}}
}
func (this *MapSum) Insert(key string, val int) {
idx := sort.Search(len(this.items), func(i int) bool {
return this.items[i].key >= key
})
if idx == len(this.items) {
this.items = append(this.items, Item{key, val})
return
}
if this.items[idx].key == key {
this.items[idx].value = val
return
}
this.items = append(this.items, Item{key, val})
sort.Sort(this.items)
}
func (this *MapSum) Sum(prefix string) int {
sum := 0
idx := sort.Search(len(this.items), func(i int) bool {
return this.items[i].key >= prefix
})
for i := idx; i < len(this.items); i++ {
if !strings.HasPrefix(this.items[i].key, prefix) {
break
}
sum += this.items[i].value
}
return sum
}