美文网首页
leecode:01 两数之和

leecode:01 两数之和

作者: 小强不是蟑螂啊 | 来源:发表于2019-06-18 15:57 被阅读0次

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

遍历两次的我就不写了,写一下用hash对应值来求和,只遍历一次:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum =function(nums, target) {   
    var obj = {},rest,result;
    for(var i=0;i<nums.length;i++){
         rest = target - nums[i];
         if(typeof obj[rest]  != 'undefined' ){
             return [obj[rest],i]
         } else {
             obj[nums[i]] = i;
         }
    }
    return []
};

结果超过了95%的提交,说名效果很好


image.png

相关文章

  • leecode:01 两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • LeeCode01-两数之和

    题目来源: https://leetcode-cn.com/problems/two-sum/[https://l...

  • leecode刷题(8)-- 两数之和

    leecode刷题(8)-- 两数之和 两数之和 描述: 给定一个整数数组 nums 和一个目标值 target,...

  • leecode 1 两数之和

    求数组内满足特定值的元素索引 方法一 这种方法容易想,时间复杂度为n2 方法二 这种方法不是很容易想,但很有趣 5...

  • Leecode[1] 两数之和

    题目 给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的...

  • 2018-07-12

    C++ map hashmap java hashmap 对比分析 首先 这个是在做leecode上的两数之和时遇...

  • LC吐血整理-Array篇

    github-Leecode_summary 1. 两数之和 hash() 用于获取取一个对象(字符串或者数值等)...

  • 01——两数之和

    给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下...

  • 01两数之和

    2019年04月15日 Day01 级别:简单 LeetCode 01 题目: 两数之和 给定一个整数数组 ...

  • Leecode[15] 三数之和

    题目 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b...

网友评论

      本文标题:leecode:01 两数之和

      本文链接:https://www.haomeiwen.com/subject/saifqctx.html