资讯专栏INFORMATION COLUMN

LeetCode 01 || twoSum

sutaking / 2069人阅读

摘要:有一个整数数组,返回其中两个值之和为指定值的索引。遍历数组每个元素,获与每个元素的差值,然后利用数组的方法在剩余的数组值中查找差值,如果有,则将当前索引与方法查找的索引保存在数组中,返回。初版,总算完成了。

two Sum

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].
第一版

思路:先想到的肯定是两次循环。遍历数组每个元素,获target与每个元素的差值,然后利用数组的indexOf()方法在剩余的数组值中查找差值,如果有,则将当前索引与indexOf()方法查找的索引保存在数组中,返回。

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var twoSum = function(nums, target) {
        var result = [];
        for(var i=0; i

结论:耗时335ms,只有17%的beats。。。初版,总算完成了。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/81923.html

相关文章

  • [Leetcode] 3Sum 4Sum 3Sum Closet 多数和

    摘要:为了避免得到重复结果,我们不仅要跳过重复元素,而且要保证找的范围要是在我们最先选定的那个数之后的。而计算则同样是先选一个数,然后再剩下的数中计算。 2Sum 在分析多数和之前,请先看Two Sum的详解 3Sum 请参阅:https://yanjia.me/zh/2019/01/... 双指针法 复杂度 时间 O(N^2) 空间 O(1) 思路 3Sum其实可以转化成一个2Sum的题,...

    trigkit4 评论0 收藏0
  • [LeetCode] 170. Two Sum III - Data structure desig

    Problem Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure.find - Find if there exists any pair of number...

    dack 评论0 收藏0
  • LeetCode 之 JavaScript 解答第一题 —— 两数之和(Two Sum)

    摘要:步骤遍历数组数据,将根据下标和元素值存放到散列表中。目标值减去数组元素差值并在散列表中查找。测试法三一遍哈希表算法思路遍历目标值减去数组元素的差值同时判断该值在散列表中是否存在差值,如果存在,则返回否则将数据加入到散列表中。 Time:2019/4/1Title:Two SumDifficulty: simpleAuthor:小鹿 题目一:Two Sum Given an array ...

    k00baa 评论0 收藏0
  • [Leetcode] Two Sum 两数和

    摘要:如果存在该差值,说明存在两个数之和是目标和。而哈希表方法中的则可以换成。如果要求的不是两个数和和,而是找两个数之差为特定值的配对呢同样用哈希表可以解决。 Two Sum Given an array of integers, find two numbers such that they add up to a specific target number.The function t...

    pkhope 评论0 收藏0
  • LeetCode 167:两数之和 II - 输入有序数组 Two Sum II - Input a

    摘要:公众号爱写给定一个已按照升序排列的有序数组,找到两个数使得它们相加之和等于目标数。函数应该返回这两个下标值和,其中必须小于。示例输入输出解释与之和等于目标数。 公众号: 爱写bug(ID:icodebugs) 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。...

    张春雷 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<