zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Two Sum

    Two Sum

    Given an array of integers, 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.

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

    https://leetcode.com/problems/two-sum/


    提示用map做,暴力O(n^2)也能解。

    有个case比较狡猾,中招了。

    Input: [-3,4,3,90], 0
    Output: undefined
    Expected: [1,3]

     1 /**
     2  * @param {number[]} nums
     3  * @param {number} target
     4  * @return {number[]}
     5  */
     6 var twoSum = function(nums, target) {
     7     var map = {};
     8     for(var i in nums){
     9         if(map[nums[i]] !== undefined){
    10             return [parseInt(map[nums[i]]) + 1, parseInt(i) + 1];
    11         }else{
    12             map[target - nums[i]] = i;
    13         }   
    14     }
    15 };
    16 
    17 function test(){    
    18     console.log(twoSum([3,4,-3,90], 0));  //13
    19     console.log(twoSum([2,7,11,15], 9));  //12
    20     console.log(twoSum([0,4,3,9], 9));  //14
    21     console.log(twoSum([0,4,3,0], 0));  //14
    22     console.log(twoSum([-3,4,3,90], 0));  //13
    23 }
     
  • 相关阅读:
    解题报告:luogu P3853 [TJOI2007]路标设置
    解题报告:luogu P2678 跳石头
    SG函数
    解题报告:CF622F
    解题报告:luogu P1144 最短路计数
    树剖小结(简述)
    LCA之tarjan离线
    %你赛2020.2
    一个小证明(题解 P5425 Part1)
    科创版简介
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4525249.html
Copyright © 2011-2022 走看看