• 算法: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];
    };
    */
    

      

  • 相关阅读:
    bzoj 2002: [Hnoi2010]Bounce 弹飞绵羊(分块算法)
    hdu 3652 "B-number"(数位DP)
    数位DP+其他
    hdu 4352 "XHXJ's LIS"(数位DP+状压DP+LIS)
    CodeForces 55D "Beautiful numbers"(数位DP+离散化处理)
    洛谷 P1163"银行贷款"(二分)
    ZOJ-3872-Beauty of Array-思维
    洛谷P3951 小凯的疑惑
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/pangxiaox/p/7028834.html
Copyright © 2020-2023  润新知