LeetCode刷题记: 两数相加
2017-03-29 20:59
567 查看
写在前面:
为了提升算法水平与熟悉JavaScript基本功能,决定去LeetCode做做算法题,这个网站支持多种语言,当然包括最火热的JavaScript啦,我是按照页面默认排序写的,无视难度,简单的自己写,然后Google更优答案,困难的自己好久都想不出的话就直接Google答案1. Two Sum (两数相加)
题目
给定一个整数数组,返回两个数的index,使它们相加为一个特定的值样例
提供: nums = [2, 7, 11, 15], target = 9, 因为 nums[0] + nums[1] = 2 + 7 = 9, 所以 return [0, 1].
思路
为了降低复杂度,使用JavaScript的内置对象 Map或者使用纯数组来进行操作样例一
/** * @param {number[]} nums * @param {number} target * @return {number[]} * 这种先生成查找表的方法不能使用数组进行存储,因为如果是输入的nums有重复的数的话,比如 [1,4,4,5],结果会是这样: * 1 -> 0 * 4 -> 2 * 5 -> 3 */ var twoSum = function (nums, target) { // 用于记录数组nums的长度 const length = nums.length; // 实例化一个Map对象 let hash = new Map(); let index = 0; for (index = 0; index < length; index++) { // 设置 hashMap 的 <key, value>,用于后面比较取值 hash.set(nums[index], index); } // 遍历数组中的每一个数,求出另一个与其相加可以满足条件的数的值,存储在 @param numToFind 中 let numToFind; for( index = 0; index < length; index++) { numToFind = target - nums[index]; // 查询 hashMap 中对应的值是否有对应的index,而且不能是当前数的下标(防止出现 3 + 3 = 6,但数组nums中只有一个3这样的情况) if (hash.has(numToFind) && index !== hash.get(numToFind)) { return [index, hash.get(numToFind)]; } } };
样例二
当然,你也可以在一个循环中完成/** * @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; }
相关文章推荐
- 链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))
- Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告
- [leetcode]两数相加
- [LeetCode]371.Sum of Two Integers两数相加
- LeetCode 02. 两数相加(链表) 03.最大不重复的字符串
- leetcode算法题:两数相加(Java实现-效率超过100%提交者)
- LeetCode 2. 两数相加
- LeetCode - 两数相加
- 【LeetCode】- Two Sum(两数相加)
- Leetcode刷题记——67. Add Binary(二进制数相加)
- Leetcode 第二题,两数链表相加
- 从零打卡leetcode之day 2---两数相加
- LeetCode - 66/67 - 两数相加加法模拟
- 刷LeetCode(1)——两数相加
- [LeetCode] 2. Add Two Numbers 两数相加 @python
- LeetCode 2. Add Two Numbers(两数相加)
- [LeetCode] Add Two Numbers 两数相加
- Leetcode002--单链表两数相加
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(所有根到叶子结点组组成的数字相加)】