[LeetCode By Go 37]167. Two Sum II - Input array is sorted

题目

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解题思路

两边查找
记得找到后编号加1

代码

twoSum.go

package _167_Two_Sum2_Input_array_sorted

func TwoSum(numbers []int, target int) []int {
    var ret []int
    len1 := len(numbers)

    for i, j := 0, len1 - 1; i < j; {
        if target == numbers[i] + numbers[j] {
            i++
            j++
            ret = []int{i, j}
            break
        } else if target > numbers[i] + numbers[j] {
            i++
        } else if target < numbers[i] + numbers[j] {
            j--
        }
    }

    return ret
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/8b18bb69f7f6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞