-
leetCode - 3Sum Closest프로그래밍/algorithm 2021. 7. 21. 13:48
문제
Given an array nums of n integers 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 input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
- 3 <= nums.length <= 10^3
- -10^3 <= nums[i] <= 10^3
- -10^4 <= target <= 10^4
풀이
const threeSumClosest = function(nums, target) { nums.sort((a, b) => a - b); let result = nums[0] + nums[1] + nums[2]; for (let i = 0; i < nums.length; i++) { let low = i + 1, high = nums.length - 1, sum = 0; while (low < high) { sum = nums[i] + nums[low] + nums[high]; if (sum === target) { return target; } else if (sum < target) { while (nums[low] === nums[low + 1]) low++; low++; } else if (sum > target) { while (nums[high] === nums[high - 1]) high--; high--; } if (Math.abs(target - result) > Math.abs(target - sum)) { result = sum; }; } } return result; };
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode-4Sum(two pointer) (0) 2021.07.22 leetCode - Letter Combinations of a Phone Number(backtracking) (0) 2021.07.22 leetCode - 3sum (0) 2021.07.20 leetCode - Integer to Roman (0) 2021.07.20 leetCode - Container With Most Water (0) 2021.07.20