3Sum Closest - LeetCode
Can you solve this real interview question? 3Sum Closest - Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each inp
leetcode.com
< 문제 간단설명 >
주어진 nums 배열에서 3개의 수를 뽑아서 더했을 때, target 값과 가장 가까운 값을 반환하면 된다.
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function (nums, target) {
nums.sort((a, b) => a - b);
let result = Infinity;
for (let i = 0; i < nums.length; i += 1) {
// 하나씩 순회하면서 현재 값을 최소값으로 설정
let minNum = nums[i];
// left는 최소값의 다음부터, right는 가장 큰 값부터 시작
let [left, right] = [i + 1, nums.length - 1];
let sum = 0;
while (left < right) {
sum = minNum + nums[left] + nums[right];
// 만약 현재 sum이 저장되어있는 result 보다 target에 더 가깝다면
// result 현재 sum으로 교체
if (Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
if (sum < target) {
left += 1;
} else if (sum > target) {
right -= 1;
} else {
return sum;
}
}
}
return result;
};
'PS > LeetCode' 카테고리의 다른 글
LeetCode / Tree / 101번 / Symmetric Tree / JS (1) | 2023.05.14 |
---|---|
LeetCode / Tree / 100번 / Same Tree / JS (1) | 2023.05.14 |
LeetCode / Dynamic Programming / 416번 / Partition Equal Subset Sum / JS (0) | 2023.05.14 |
LeetCode / Dynamic Programming / 322번 / Coin Change / JS (0) | 2023.05.14 |