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

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

Open
sl1673495 opened this issue May 16, 2020 · 0 comments
Open

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

sl1673495 opened this issue May 16, 2020 · 0 comments
Labels
双指针 复习 * 1 复习了一遍的题目

Comments

@sl1673495
Copy link
Owner

sl1673495 commented May 16, 2020

  1. 两数之和 II - 输入有序数组

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

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

说明:

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

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

思路

因为是有序数组,所以可以建立两个指针,i指向数组的头部,j指向数组的尾部。

此时开始遍历,如果左右指针指向的值,相加大于目标值,说明右指针需要左移指向稍小的值再尝试,反之左指针右移,如果相加的值相等,那么答案就是两个指针的值 [i, j]

直到 i === j 循环终止。

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
let twoSum = function(numbers, target) {
  let i = 0;
  let j = numbers.length - 1;

  while (i !== j) {
    let sum = numbers[i] + numbers[j];
    if (sum > target) {
      j--;
    } else if (sum < target) {
      i++;
    } else {
      return [i + 1, j + 1];
    }
  }
};
@sl1673495 sl1673495 added 双指针 复习 * 1 复习了一遍的题目 labels May 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
双指针 复习 * 1 复习了一遍的题目
Projects
None yet
Development

No branches or pull requests

1 participant