문제 링크 : 3Sum Closest
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
const result = getCombinations(nums, 3).map(el => el.reduce((acc,cur) => acc+cur))
const tempArr = result.map(el => Math.abs(target-el))
const min = Math.min(...tempArr)
return result[tempArr.indexOf(min)]
};
const getCombinations = (arr, num) => {
const results = [];
if (num === 1) return arr.map(v => [v]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, num - 1);
const attached = combinations.map(v => [fixed, ...v]);
results.push(...attached);
});
return results;
}
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
let sum = Number.MAX_VALUE;
if(nums.length < 3) return;
nums.sort((a,b) => a - b)
for (let curr = 0; curr < nums.length; curr++) {
let left = curr + 1;
let right = nums.length - 1;
while(left < right){
tempSum = nums[curr] + nums[left] + nums[right];
if(tempSum === target) return target;
if(Math.abs(target - sum) > Math.abs(target - tempSum)) {
sum = tempSum;
}
if(tempSum < target){
left++
}
else{
right--
}
}
}
return sum;
};