Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

167. 两数之和 II - 输入有序数组 #43

Open
yankewei opened this issue Jul 20, 2020 · 0 comments
Open

167. 两数之和 II - 输入有序数组 #43

yankewei opened this issue Jul 20, 2020 · 0 comments
Labels
双指针 题目包含双指针解法 数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

说明:

返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

示例:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted

解答

双指针

题目给出:数组是已经排序的,并且有唯一的答案,那么我们可以使用双指针,一个l从数组头部遍历,一个r从数组尾部向前遍历,两个值相加,如果大于targetr指针向左移动一位,就是r--。如果小于targetl指针向右移动一位,就是l++。直到等于target,返回就可以了。

func twoSum(numbers []int, target int) []int {
    l, r := 0, len(numbers)-1
    for l <= r {
        sum := numbers[l] + numbers[r]
        if sum > target {
            r--
            continue
        }
        if sum < target {
            l++
            continue
        }
        break
    }
    return []int{l+1, r+1}
}
@yankewei yankewei added 双指针 题目包含双指针解法 数组 题目类型为数组 简单 题目难度为简单 labels Jul 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
双指针 题目包含双指针解法 数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant