-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_table_2sum.go
More file actions
64 lines (53 loc) · 787 Bytes
/
hash_table_2sum.go
File metadata and controls
64 lines (53 loc) · 787 Bytes
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
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
f, err := os.Open("2sum.txt")
if err != nil {
panic(err)
}
defer f.Close()
m := HashTable{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
str := scanner.Text()
d, err := strconv.Atoi(str)
if err != nil {
fmt.Println(err)
continue
}
m.Put(d)
}
d := map[int]bool{}
m.Range(func(k int) {
for i := -10000; i <= 10000; i++ {
if m.Exist(i - k) {
d[i] = true
}
}
})
fmt.Println(len(d))
}
type HashTable map[int]bool
func (h HashTable) Put(d int) {
h[d] = false
}
func (h HashTable) Exist(d int) bool {
_, ok := h[d]
if ok {
h[d] = true
}
return ok
}
func (h HashTable) Range(f func(int)) {
for k := range h {
if !h[k] {
h[k] = true
f(k)
}
}
}