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

      

  • 相关阅读:
    新手安装Oracle数据库指南
    新手IntelliJ IDEA入门指南
    IntelliJ IDEA 开发工具快捷键大全
    打印杨辉三角
    个人作业-Alpha项目测试
    第三次作业
    第二次作业
    第一次作业-林楠-201731062428
    手把手教你实现在Monaco Editor中使用VSCode主题
    一文搞懂jsBridge的运行机制
  • 原文地址:https://www.cnblogs.com/pangxiaox/p/7028834.html
Copyright © 2011-2022 走看看