zoukankan      html  css  js  c++  java
  • 算法:JavaScript两数之和

    题目

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].



    代码

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
     //[2, 7, 11, 15]  9
     //把差存进数组,如果当前遍历数组有和差相等的值则把当前值的小标和差的下标输出来
     var twoSum = function(nums, target)  {
        let theSet = []
        for(let i = 0; i < nums.length; i++){
           if( theSet.indexOf( nums[i] )  !== -1){   //当前数和数组匹对是否存在
             return [theSet.indexOf( nums[i] ), i];     //如果有则返回当前值再数组中的位置和当前下标
           }else{
            theSet.push(target - nums[i] );//如果数组没有当前值则相减把差存进去数组  9-2=7 i=1 -- 9-7=2 i=2 -- 9-11=-2 i=3 -- 9-15=-6 i=4
           }
        }
       return [0,0];
    };
     /*
    var twoSum = function(nums, target) {
        var arr = [];
        var num = [];
       
       
        
        /*
        for(var i = 0;i<nums.length;i++){
            for(var j = i+1; i< nums.length; j++){
                if(nums[i] ==  target - nums[j] ){
                arr = [i,j];
                return arr;
                }
            }
            
        }
        ***
    };
    
    var twoSum = function(nums, target) {
        const diffs = new Map();
        const j = nums.findIndex((a, i) => diffs.has(target - a) || diffs.set(a, i) && 0);
        return [diffs.get(target - nums[j]), j];
    };
    */
    

      

  • 相关阅读:
    HDU2546(01背包)
    HDU4283(KB22-G)
    POJ1651(KB-E)
    POJ2955(KB22-C 区间DP)
    POJ3264(KB7-G RMQ)
    POJ3468(KB7-C 线段树)
    POJ3616(KB12-R dp)
    Ubuntu16.04安装opencv for python/c++
    华中农业大学第五届程序设计大赛网络同步赛-L
    华中农业大学第五届程序设计大赛网络同步赛-K
  • 原文地址:https://www.cnblogs.com/pangxiaox/p/7028834.html
Copyright © 2011-2022 走看看