javascript实现leetcode之two sum
2017-02-15 01:03
381 查看
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:
给定一个整数数组,寻找两个整数使它们的和等于target,并且返回它们的下标。
毕竟第一题,解题思路还是比较简单地,最简单的方法就是遍历两次数组去加吧阿西吧。
其实用js对象实现简单hashMap就可以在线性的时间里解决问题
for循环每次执行的时候,以nums[i]的值为key,下标i为value存入exsit对象中。每次循环时会先去查找target-nums[i]有没有存在,如果存在,则返回i和值为target-nums[i]的下标,即exsit[target-nums[i]](exsit中存的key为数组中元素值,value为数组元素下标)
执行效率如下
毕竟小菜鸡,连90%都没有进入,以后需要多多努(抄)力(袭)啊!
我的github地址(leetcode部分)
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].
给定一个整数数组,寻找两个整数使它们的和等于target,并且返回它们的下标。
毕竟第一题,解题思路还是比较简单地,最简单的方法就是遍历两次数组去加吧阿西吧。
其实用js对象实现简单hashMap就可以在线性的时间里解决问题
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { var len = nums.length; var exist = {} for(var i = 0; i < len; i++){ if (exist[target - nums[i]] !== undefined){ return [exist[target-nums[i]], i]; } exist[nums[i]] = i } };
for循环每次执行的时候,以nums[i]的值为key,下标i为value存入exsit对象中。每次循环时会先去查找target-nums[i]有没有存在,如果存在,则返回i和值为target-nums[i]的下标,即exsit[target-nums[i]](exsit中存的key为数组中元素值,value为数组元素下标)
执行效率如下
毕竟小菜鸡,连90%都没有进入,以后需要多多努(抄)力(袭)啊!
我的github地址(leetcode部分)
相关文章推荐
- leetcode two sum python 实现
- 【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】
- leetcode-Two sum(最佳思路以及python代码实现)
- Two Sum Leetcode 解法实现
- LeetCode(1) Two Sum实现
- [LeetCode] Sum of Two Integers(用位运算实现加法)
- leetcode:1. Two Sum(Java实现)
- [leetcode]Two Sum C++ python实现
- LeetCode ---- Two Sum (Java Lua 实现)
- leetcode1 Two Sum(JavaScript)
- [LeetCode]1 Two Sum(C++,Python实现)
- leetcode 371 Sum of Two Integers java实现
- LeetCode[1] Two Sum (java实现)
- [leetcode]1. Two Sum -- JavaScript 代码
- LeetCode-1-Two Sum(C语言实现)
- LeetCode twosum C++ map实现
- LeetCode Two Sum 之 JavaScript 多种解法
- LeetCode Javascript实现 344. Reverse String 292. Nim Game 371. Sum of Two Integers
- [leetcode] Sum of Two Integers--用位运算实现加法运算
- [LeetCode][1]Two Sum解析 -Java实现