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];
    };
    */
    

      

  • 相关阅读:
    rapidjson 使用
    【设计模式】模板方法模式
    【设计模式】策略模式
    【设计模式】建造者模式
    【设计模式】享元模式
    /dev/sda1 contains a file system with errors,check forced.
    如何编写高效的Python的代码
    VsCode 调试 Python 代码
    Python 使用 pyinstaller 打包 代码
    初次使用git上传代码到github远程仓库
  • 原文地址:https://www.cnblogs.com/pangxiaox/p/7028834.html
Copyright © 2011-2022 走看看