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 - 输入有序数组 #38

Closed
sailei1 opened this issue May 22, 2019 · 0 comments
Closed

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

sailei1 opened this issue May 22, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 22, 2019

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

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

说明:

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

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

解法:
target 减一个小值, 寻找另一个值 返回下标

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(numbers, target) {
      for(let i=0;i<numbers.length;i++){
           let f=target-numbers[i];
          for(let l=i+1;l<numbers.length;l++){
              if(f===numbers[l]){
                  return [i+1,l+1];
              }
          }
          
      }
};
@sailei1 sailei1 closed this as completed May 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant