Skip to content

Instantly share code, notes, and snippets.

@kostix
Created October 12, 2021 16:46
Show Gist options
  • Save kostix/c90ba79a9c4b2c66633471f31bf9056f to your computer and use it in GitHub Desktop.
Save kostix/c90ba79a9c4b2c66633471f31bf9056f to your computer and use it in GitHub Desktop.
twosums$ go test -bench=. -run=none -benchmem .
goos: linux
goarch: amd64
BenchmarkTwoSum1-8 14698284 149 ns/op 16 B/op 1 allocs/op
BenchmarkTwoSum2-8 7724497 138 ns/op 16 B/op 1 allocs/op
PASS
ok _/home/kostix/tmp/twosums 3.508s
package main
import "testing"
func twoSum1(nums []int, target int) []int {
hMap := map[int]int{}
for i := range nums {
complement := target - nums[i]
_, ok := hMap[complement]
if ok == true {
return []int{i, hMap[complement]}
}
hMap[nums[i]] = i
}
return nil
}
func twoSum2(nums []int, target int) []int {
hMap := map[int]int{}
for i, val := range nums {
complement := target - val
_, ok := hMap[complement]
if ok == true {
return []int{i, hMap[complement]}
}
hMap[val] = i
}
return nil
}
func BenchmarkTwoSum1(b *testing.B) {
nums := []int{2, 7, 11, 15}
target := 9
b.ResetTimer()
var whatever []int
for i := 0; i < b.N; i++ {
whatever = twoSum1(nums, target)
}
_ = whatever
}
func BenchmarkTwoSum2(b *testing.B) {
nums := []int{2, 7, 11, 15}
target := 9
b.ResetTimer()
var whatever []int
for i := 0; i < b.N; i++ {
whatever = twoSum2(nums, target)
}
_ = whatever
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment