zoukankan      html  css  js  c++  java
  • javascript leetcode1

    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[]}
     */
     var twoSum = function(nums, target) {
         for(var i=0,len=nums.length; i<len-1; i++){
             for(var j=i+1; j<len; j++){
                 if(nums[j] == target - nums[i]){
                     return [i,j];
                 }
             }
         }
         return false;
    };    
    

      

    方法二:哈希表法

    思路:首先使用哈希表记录数组中每个元素对应的数组的下标,key为元素,value为下标。然后就可以遍历数组中 的每一个元素,每次都可以轻易地计算出该趟元素的补(target-nums[i]),如果在哈希表中查询到这个值,就可以 获取到其对应的下标,那么,满足条件的元素的下标为该趟元素的下标和它的补在哈希表中的value。

    考虑到javascript中对象具有“哈希特性”,使用对象作为“哈希表”

    代码:

         
    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var twoSum = function(nums, target) {
        var map = {};
        for(var i=0,len=nums.length; i<len; i++){
            //record
            map[nums[i]] = i;
        }
        for(var i=0,len=nums.length; i<len; i++){
            var complement = target - nums[i];
            var temp = map[complement];
            if(temp !== undefined && temp !== i){
                return [i,temp];
            }
        }
        return false;
    };
    

      

  • 相关阅读:
    JavaScript中的事件循环
    CSS布局
    Tomcat相关
    C#参数中ref和out的区别
    angular启动4200端口后,如何停止监听4200端口
    表联接(交叉连接,内联,外联)
    如何使用vs自带的反编译工具Lldasm
    软件架构需要注意的几点,待补充。。。
    SqlServer中With(NOLOCK)
    TypeScript preview
  • 原文地址:https://www.cnblogs.com/githubMYL/p/8982155.html
Copyright © 2011-2022 走看看