본문 바로가기
LeetCode

[LeetCode] 16. 3Sum Closest

by JungSeung 2023. 10. 23.
728x90

https://leetcode.com/

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 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).

 

Example 2:

Input: nums = [0,0,0], target = 1
Output: 0
Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).

 

Constraints:

  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4

 

Code :

var threeSumClosest = function(nums, target) {
    let result = Number.MAX_VALUE; // 결과를 담을 변수를 초기화합니다.
    let number = Number.MAX_VALUE; // 숫자를 초기화합니다.
    nums.sort((a, b) => a - b); // 주어진 배열을 오름차순으로 정렬합니다.
    // 주어진 배열을 순회하며 가장 가까운 세 수의 합을 계산합니다.
    for (let start = 0; start < nums.length; start++) {
        let left = start+1; // 왼쪽 포인터를 초기화합니다.
        let right = nums.length-1; // 오른쪽 포인터를 초기화합니다.
        // 왼쪽 포인터가 오른쪽 포인터보다 작은 동안 반복합니다.
        while (left < right) {
            // 주어진 target과 세 수의 합의 차이가 현재 숫자보다 작으면 결과를 업데이트합니다.
            if (Math.abs(target - (nums[start] + nums[left] + nums[right])) < number) {
                result = nums[start] + nums[left] + nums[right]; // 결과를 업데이트합니다.
                number = Math.abs(target - (nums[start] + nums[left] + nums[right])); // 숫자를 업데이트합니다.
            }
            if (nums[start] + nums[left] + nums[right] > target) { // 합이 target보다 큰 경우
                right--; // 오른쪽 포인터를 감소시킵니다.
            } else if (nums[start] + nums[left] + nums[right] == target) { // 합이 target과 같은 경우
                break; // 반복을 종료합니다.
            } else { // 합이 target보다 작은 경우
                left++; // 왼쪽 포인터를 증가시킵니다.
            }
        }
    }
    return result; // 결과를 반환합니다.
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 18. 4Sum  (2) 2023.10.24
[LeetCode] 17. Letter Combinations of a Phone Number  (2) 2023.10.24
[LeetCode] 15. 3Sum  (0) 2023.10.20
[LeetCode] 14. Longest Common Prefix  (0) 2023.10.20
[LeetCode] 13. Roman to Integer  (2) 2023.10.19