Created
October 28, 2018 23:57
-
-
Save geowa4/4c292290437a552e7a59709bcb81301c to your computer and use it in GitHub Desktop.
Find pairs that equal target
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
//Given a list of numbers and a number k, return whether any two numbers from the list add up to k. | |
//For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. | |
import ( | |
"fmt" | |
"math/rand" | |
) | |
func pairsFill(size int) []int { | |
slice := make([]int, 0, size) | |
for i := 0; i < size; i++ { | |
slice = append(slice, int(rand.Float32()*10)) | |
} | |
return slice | |
} | |
func hasPairForSum(nums []int, k int) bool { | |
seen := make(map[int]bool) | |
for _, n := range nums { | |
if _, present := seen[k-n]; present { | |
return true | |
} | |
seen[n] = true | |
} | |
return false | |
} | |
func main() { | |
var ( | |
nums []int | |
k int | |
) | |
nums, k = pairsFill(6), 10 | |
fmt.Println(nums, k, hasPairForSum(nums, k)) | |
nums, k = pairsFill(6), 7 | |
fmt.Println(nums, k, hasPairForSum(nums, k)) | |
nums, k = pairsFill(6), 7 | |
fmt.Println(nums, k, hasPairForSum(nums, k)) | |
nums, k = pairsFill(1000000), 7 | |
fmt.Println(hasPairForSum(nums, k)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment