16. 3Sum Closest

2021. 11. 2. 11:46·Algorithm
 

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

정수가 담긴 배열 nums, 특정한 정수 target이 주어진다.

nums의 정수 3개를 골라서 더한 합이 target과 가장 가깝게 되는 정수 3개의 합을 반환하는 문제다.

 

예시

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

Input: nums = [0,0,0], target = 1
Output: 0

1. 3-Pointer

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        answer = 0
        answer_gap = float("inf")
        for i in range(0, len(nums) - 2):
            start, end = i + 1, len(nums) - 1

            while start < end:
                cur = nums[i] + nums[start] + nums[end]
                if abs(cur - target) < answer_gap:
                    answer_gap = abs(cur - target)
                    answer = cur

                if cur < target:
                    start += 1
                elif cur > target:
                    end -= 1
                elif cur == target:
                    return cur

        return answer

3-pointer를 이용해 해결하는 문제다.

3 pointer를 이용해 순회하면서 answer_gap을 작게 만드는 answer를 저장하고 반환하는 것으로 해결할 수 있다.

 

3-pointer를 구현하는 문제는 아래 포스팅을 참고.

 

15. 3Sum

3Sum - 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 1. Two Pointer를 사용한 풀..

doljae.tistory.com

 

'Algorithm' 카테고리의 다른 글

404. Sum of Left Leaves  (0) 2021.11.11
392. Is Subsequence  (0) 2021.11.09
41. First Missing Positive  (0) 2021.11.01
148. Sort List  (0) 2021.10.30
329. Longest Increasing Path in a Matrix  (0) 2021.10.28
'Algorithm' 카테고리의 다른 글
  • 404. Sum of Left Leaves
  • 392. Is Subsequence
  • 41. First Missing Positive
  • 148. Sort List
Doljae
Doljae
  • Doljae
    Zero to Hero
    Doljae
  • 전체
    오늘
    어제
    • 분류 전체보기 (349)
      • Programming (54)
      • Algorithm (161)
      • Review (102)
      • Career (8)
      • Diary (18)
      • Shorts (4)
      • Temp (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    java
    라인
    db
    AI
    개발자
    나는 리뷰어다
    코딩
    나는리뷰어다
    한빛미디어
    line
    2022
    코딩테스트
    ChatGPT
    database
    컨퍼런스
    면접
    leetcode
    sql튜닝
    PYTHON
    인프콘
    jpa
    2023
    mysql
    BOJ
    공채
    2021
    백준
    회고
    프로그래머스
    sql
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Doljae
16. 3Sum Closest
상단으로

티스토리툴바