zoukankan      html  css  js  c++  java
  • 给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。

    描述

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target

    你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1

    你可以假设只有一组答案。

    样例

    Example1:
    给出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].
    Example2:
    给出 numbers = [15, 2, 7, 11], target = 9, 返回 [1, 2].

     1 /**
     2  * @param numbers: An array of Integer
     3  * @param target: target = numbers[index1] + numbers[index2]
     4  * @return: [index1, index2] (index1 < index2)
     5  */
     6 const twoSum = function (numbers, target) {
     7     for (let i = 0; i < numbers.length; i++) {
     8         let newNumbers = [...numbers]
     9         let num1 = numbers[i]
    10         let num2 = target - num1
    11         newNumbers.splice(i, 1)
    12         let num2Index = newNumbers.indexOf(num2)
    13         if (num2Index > -1) {
    14             if (num2Index >= i) {
    15                 return [i, num2Index + 1]
    16             }
    17         }
    18     }
    19 }
     
  • 相关阅读:
    掌门教育首通和续费文案整理
    python upload file遇到的坑,整理如下
    测试难题(转)
    敏捷测试与传统测试的区别
    质量体系
    幂等校验
    Charles常用功能整理
    测试难题
    敏捷测试与传统测试的区别
    质量体系
  • 原文地址:https://www.cnblogs.com/chentingjun/p/10543343.html
Copyright © 2011-2022 走看看