使用映射函数而不是嵌套循环条件 JS [英] Using a map function instead of a nested loop condition JS

查看:43
本文介绍了使用映射函数而不是嵌套循环条件 JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下函数,它接受一个数字数组和一个目标值,如果可以添加数组中的任意 2 个数字来给出目标值,则该函数返回 true,否则返回 false.例如,如果数组 = [5,4,2,3,1] 且目标 = 9,则函数应返回 true 为 5+4=9.但是,如果 target = 10,该函数应该返回 false,因为数组中的 2 个数字不能相加得到 10.

I have the following function which takes in an array of numbers and a target value, if any 2 of the numbers in the array can be added to give the target value, the function returns true, if not it returns false. E.g if array = [5,4,2,3,1] and target = 9, the function should return true as 5+4=9. However if target = 10, the function should return false as no 2 numbers in the array can be added to give 10.

function Solution(array,target) {
    for (var i = 0;i<array.length;i++) {
      for (var j=0;j!=i && j<array.length;j++) {
        if (array[i] + array[j] == target) {
        return true
      }
    }
  }
  return false
}

上述功能按预期工作,但我认为这不是一个好方法,有人可以告诉我使用地图功能的更有效方法吗?

The above function works as expected however I don't think this is a good way of doing it, can anybody show me a more efficient way using a map function?

推荐答案

您可以将哈希表与所需的增量作为键.

You could take a hash table with the needed delta as key.

这种方法只需要一次迭代.

This approach needs only one iteration.

function solution(array, target) {
    const seen = {};
    for (const value of array) {
        if (seen[value]) return true;
        seen[target - value] = true;
    }
    return false;
}

console.log(solution([5, 4, 3, 2, 1], 9));  //  true
console.log(solution([5, 4, 3, 2, 1], 10)); // false

这篇关于使用映射函数而不是嵌套循环条件 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆