[英]Javascript: Write a function that takes in an array, and then returns an array with only unique numbers, only arrays removed
[英]An unique arrays of numbers from an Array with JavaScript
谁能告诉我如何解决这个问题:
我尝试使用 array.map、array.filter、array.reduce 执行此操作,但没有得到结果:
写一个 function putNum(arrayOfNum: number[], num: number),它会从 arrayOfNum 中找到所有可能的数字组合,其总和等于数字。 其中:
@param arrayOfNum: 数字[]
@param num: 数字[]
@return 数组<数组<数字>>
function putNum(arrayOfNum, num) {
***// write code only inside this function***
return [[1, 2], [3]];
}
// console.log(putNum([8, 2, 3, 4, 6, 7, 1], 99)); => []
// console.log(putNum([8, 2, 3, 4, 6, 7, 1], 5)); => [[2, 3], [4, 1]]
// console.log(putNum([1, 2, 3, 4, 5, 6, 7, 8], 8)); => [[1, 3, 4], [1, 2, 5], [3, 5], [2, 6], [1, 7], [8]]
let resultnum = result.filter(e => typeof e === 'number' && e > 0); // to make a new array with nums > 0
以优化方式解决此问题的最佳方法是使用 hash map
let twoSum = (array, sum) => {
let hashMap = {},
results = []
for (let i = 0; i < array.length; i++){
if (hashMap[array[i]]){
results.push([hashMap[array[i]], array[i]])
}else{
hashMap[sum - array[i]] = array[i];
}
}
return results;
}
console.log(twoSum([10,20,40,50,60,70,30],50));
Output:
[ [ 10, 40 ], [ 20, 30 ] ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.