Skip to content

Instantly share code, notes, and snippets.

@kostix
Created October 12, 2021 16:46
Show Gist options
  • Select an option

  • Save kostix/c90ba79a9c4b2c66633471f31bf9056f to your computer and use it in GitHub Desktop.

Select an option

Save kostix/c90ba79a9c4b2c66633471f31bf9056f to your computer and use it in GitHub Desktop.

Revisions

  1. kostix created this gist Oct 12, 2021.
    7 changes: 7 additions & 0 deletions session.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    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
    59 changes: 59 additions & 0 deletions twosum_test.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    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
    }