1. 两个数的和用map 当数组顺序的时候也可以使用二分查找
let nums = [2, 7, 11, 17],
target = 9;
function twoSum(nums) {
let map = new Map();
let length = nums.length;
for (let i = 0; i < length; i++) {
if (map.has(target - nums[i])) {
return [map.get(target - nums[i]), i];
} else {
map.set(nums[i], i);
}
}
return -1;
}
let res = twoSum(nums);
console.log(res); //[ 0, 1 ]
2. 三个数的和为指定值target
需要先对数组arr进行排序,然后用set记录,
let arr = [1, 2, 7, 6, 2, 9, 0]
const threeSum = function(nums, target) {
let result = [];
nums.sort((a, b) => a - b);
for (let i = 0; i < nums.length; i++) {
while (nums[i] === nums[i - 1]) {
i++;
}
let set = new Set();
let first = nums[i];
let j = i + 1;
while (j < nums.length) {
let second = target - nums[j] - first;
if (set.has(second)) {
result.push([first, second, nums[j]]);
while (nums[j] === nums[j - 1]) {
j++;
}
}
set.add(nums[j]);
j++;
}
}
return result;
}
let res = threeSum(arr, 10);
console.log(res); //[ [ 0, 1, 9 ], [ 1, 2, 7 ], [ 2, 2, 6 ] ]
3. 从数组中取出N个数和为指定数值
let arr = [1, 2, 3, 4];
let N = 3;
let M = 6;
const search = function(arr, count, sum) {
const getCount = num => {
let count = 0;
while (num) {
num &= (num - 1);
count++;
}
return count;
}
let len = arr.length,
bit = 1 << len,
res = [];
for (let i = 1; i < bit; i++) {
if (getCount(i) === count) {
let s = 0,
temp = [];
for (let j = 0; j < len; j++) {
if (i & 1 << (len - 1 - j)) {
s += arr[j];
temp.push(arr[j]);
}
}
if (s === sum) {
res.push(temp)
}
}
}
return res;
}
let res = search(arr, N, M);
console.log(res);//[ [ 1, 2, 3 ] ]