Created
September 24, 2018 10:44
-
-
Save namtx/fab6da8aa844c72867bd41901a329d8b to your computer and use it in GitHub Desktop.
two-sum-ii-input-array-is-sorted (https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/)
This file contains hidden or 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 | |
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