File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ TwoSum takes a target sum and any number of NON-REPEATING integers and returns
3
+ the two integers that add up to the target if they exist.
4
+ For example, with a target of 5, and the list of integers 1 2 3 4
5
+ the algorithm would return [2,3]
6
+ */
7
+ package main
8
+
9
+ import (
10
+ "bufio"
11
+ "fmt"
12
+ "os"
13
+ "strconv"
14
+ "strings"
15
+ )
16
+
17
+ func main () {
18
+ fmt .Printf ("Input Target Sum: " )
19
+ var target int
20
+ fmt .Scan (& target )
21
+ fmt .Printf ("Input Array of Integers: " )
22
+ var values []int
23
+ scanner := bufio .NewScanner (os .Stdin )
24
+ scanner .Scan ()
25
+ values = numbers (scanner .Text ())
26
+
27
+ fmt .Println (twoSum (values , target ))
28
+ }
29
+
30
+ func twoSum (nums []int , target int ) []int {
31
+ // key is complement, value is index
32
+ comps := make (map [int ]int , len (nums ))
33
+ for i , val := range nums {
34
+ if index , ok := comps [val ]; ok {
35
+ return []int {nums [index ], nums [i ]}
36
+ }
37
+ comps [target - val ] = i
38
+ }
39
+ return []int {}
40
+ }
41
+
42
+ func numbers (s string ) []int {
43
+ var n []int
44
+ for _ , f := range strings .Fields (s ) {
45
+ i , err := strconv .Atoi (f )
46
+ if err == nil {
47
+ n = append (n , i )
48
+ }
49
+ }
50
+ return n
51
+ }
You can’t perform that action at this time.
0 commit comments