方法1:双循环

  1. var nums = [1,4,2,6,9];
  2. var target = 7;
  3. function twoSum(nums,target){
  4. var arrs = [];
  5. for(let i=0;i<nums.length;i++){
  6. for(let j=i+1;j<nums.length;j++){
  7. if(nums[i]+nums[j]===target){
  8. arrs.push(i,j);
  9. return arrs
  10. }
  11. }
  12. }
  13. }
  14. console.log(twoSum(nums,target)) //[0,3]

方法2:map()

  1. <script>
  2. //map方法
  3. var nums = [1, 2, 3, 4, 5];
  4. var target = 6;
  5. var twoSum = function (nums, target) {
  6. // let arrs =new Map()
  7. // arrs.has()//判断键值对中是否存在该键
  8. // arrs.get()//如果有的话 判定nums中与指定键相关联的值
  9. // arrs.set()//给map 中添加该键值
  10. let arrs = new Map()
  11. // 1.对nums遍历
  12. for (let i = 0; i < nums.length; i++) {
  13. if (arrs.has(target - nums[i])) {
  14. return [arrs.get(target - nums[i]), i]
  15. }
  16. arrs.set(nums[i], i)
  17. }
  18. };
  19. console.log(twoSum(nums, target));
  20. //bug 满足多种情况只会输出一种
  21. </script>