문제링크
3Sum Closest - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
이전에 풀었던 3Sum과 유사한 문제였다.
정수로 이루어진 배열 nums와 target Number가 주어질때
배열의 3가지 수를 합한 값(3Sum)이 target Number와 가장 가까운 경우 합한 값(3Sum)을 출력하는 문제이다.
접근 방법
3Sum과 마찬가지로 제일 왼쪽 수를 고정하고 start, end를 통해 3가지 요소의 합을 구하고
target값과 비교하며 minGap을 업데이트 하는 방식으로 진행하였다.
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
let minGap = 10e9;
let gap = 0;
let output = 0;
nums.sort((a,b) => a - b);
for(let fixed = 0; fixed < nums.length - 2; fixed++){
let start = fixed+1, end = nums.length - 1;
while(start < end){
let sum = nums[fixed] + nums[start] + nums[end];
gap = Math.abs(target - sum);
if(target > sum) start++;
else if(target < sum) end--;
else return sum
if(minGap > gap){
minGap = gap;
output = sum;
}
}
}
return output
};
'코딩테스트 > LeetCode' 카테고리의 다른 글
[LeetCode] Non-decreasing Array (0) | 2022.06.25 |
---|---|
[LeetCode] Valid Parentheses (0) | 2022.06.24 |
[LeetCode] 3Sum (0) | 2022.06.23 |
[LeetCode] Furthest Building You Can Reach (0) | 2022.06.21 |
[LeetCode] search-suggestions-system (0) | 2022.06.19 |