KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (487)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (432)
      • 백준 (187)
      • Programmers (105)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • Level1
  • Level 1
  • C++
  • C
  • tree
  • 백준
  • js
  • recursion
  • 수학
  • 정렬
  • 제코베 JS 100제
  • Level 2
  • Level 0
  • 다이나믹 프로그래밍
  • programmers
  • string
  • LeetCode
  • 그래프
  • codeup
  • 문자열

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Two Pointer / 16번 / 3Sum Closese / JS

2023. 5. 14. 19:20

< 문제 바로가기 >

 

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
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Tree / 101번 / Symmetric Tree / JS
    • LeetCode / Tree / 100번 / Same Tree / JS
    • LeetCode / Dynamic Programming / 416번 / Partition Equal Subset Sum / JS
    • LeetCode / Dynamic Programming / 322번 / Coin Change / JS
    KimMinJun
    KimMinJun

    티스토리툴바