Two Sum II

View on LeetCode

Question

You're given a list of numbers sorted in increasing order and a target value. Find two numbers that add up to the target, and return their positions (1-based).

You must solve this without using extra space — just work with the original array.

Example

Input: numbers = [1, 3, 5, 6, 9], target = 12

Output: [2, 5]

Explanation: 3 + 9 = 12


Input: numbers = [0, 2, 4, 7, 10], target = 11

Output: [3, 4]

Explanation: 4 + 7 = 11


Input: numbers = [-10, -3, 1, 2, 4], target = 1

Output: [2, 5]

Explanation: -3 + 4 = 1

My Notes

package main

import (
    "fmt"
)

func main() {
    result := twoSum([]int{-10, -3, 1, 2, 4}, 1)
    fmt.Println(result)
}

func twoSum(numbers []int, target int) []int {
    i, j := 0, len(numbers) - 1

    for {
        if numbers[i] + numbers[j] == target {
            return []int{i+1, j+1}
        }
        if numbers[j] + numbers[i] > target {
            j--
            continue
        }
        if numbers[i] < target {
            i++
        }
    }
}