-
Notifications
You must be signed in to change notification settings - Fork 2
/
twoSum.go
72 lines (61 loc) · 1.22 KB
/
twoSum.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
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
)
// number mapped to number of times you see it
type table map[int]int
func twoSum(table table, start, end int) int {
numberOfTargetValuesThatSatisfyCondition := 0
for target := start; target <= end; target++ {
if target%1000 == 0 {
fmt.Println(target)
}
for key := range table {
pairMatch := -(key - target)
if pairMatch == key {
continue
}
if _, ok := table[pairMatch]; ok {
numberOfTargetValuesThatSatisfyCondition++
break
}
}
}
return numberOfTargetValuesThatSatisfyCondition
}
func main() {
fmt.Println(twoSum(loadData("./course2/week4/twoSum/data.txt"), -100000, 100000))
}
func loadData(filepath string) table {
data := table{}
f, err := os.Open(filepath)
check(err)
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
parseRowIntoEntry(data, scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return data
}
func parseRowIntoEntry(table table, row string) {
if num, err := strconv.Atoi(row); err == nil {
if nums, ok := table[num]; ok {
nums++
table[num] = nums
} else {
table[num] = 1
}
}
}
func check(err error) {
if err != nil {
log.Panicln(err)
}
}