[leetcode, JS] 16. 3Sum Closest

mxxn·2023년 9월 15일
0

leetcode

목록 보기
77/198

문제

문제 링크 : 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;
}
  1. 시간초과

풀이

/**
 * @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;
};
  1. 풀이를 참고
  2. for문에서 sum을 비교해나가는 방식
  • Runtime 61 ms, Memory 43.9 MB
profile
내일도 글쓰기

0개의 댓글