当前位置:   article > 正文

前端算法练习day day up_前端锻炼算法

前端锻炼算法

LeetCode 算法练习

1.两数之和
题目描述

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

示例:

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

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

解题思路

(1)遍历数组,在遍历过程中求target和数组中的每个元素item的差
(2)判断target-item是否存在数组中,如果存在则返回item和差的下标

代码实现1
var twoSum = function(nums, target) {
    let result=[]
    nums.map((item,index)=>{
      let minus=target-item
      let index1=nums.indexOf(minus)
      if(index1>-1 && index1!=index)
          result.push(index,index1)
    })
    return  Array.from(new Set(result))
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/572728
推荐阅读
相关标签
  

闽ICP备14008679号