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 }
     
  • 相关阅读:
    Gradle 是什么
    Spring AOP知识
    Spring IOC常用注解
    spring 依赖注入
    Java实现基数排序
    Java实现基数排序(解决负数也可以排序)
    2020/4/10安卓开发:Spinner下拉框
    Spring ioc使用
    java实现:归并排序
    centos中docker的安装
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4525249.html
Copyright © 2011-2022 走看看