Skip to content

Instantly share code, notes, and snippets.

@namtx
Created September 24, 2018 10:44
Show Gist options
  • Save namtx/fab6da8aa844c72867bd41901a329d8b to your computer and use it in GitHub Desktop.
Save namtx/fab6da8aa844c72867bd41901a329d8b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
func main() {
nums := []int{2, 7, 11, 15}
target := 9
fmt.Println(twoSum(nums, target)) // [1, 2]
}
func twoSum(numbers []int, target int) []int {
low, high := 0, len(numbers)-1
sum := 0
for low < high {
sum = numbers[low] + numbers[high]
if sum == target {
return []int{low + 1, high + 1}
} else if sum < target {
low++
} else {
high--
}
}
return []int{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment