[Leetcode/Python] 3Sum

지구인 ㅣ 2022. 12. 7. 11:00

728x90
Top Interview Questions 의 Medium Collection에 있는 문제입니다.         
문제는 여기서 볼 수 있습니다.

 

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

 

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

 

Constraints:

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

 

Code:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        N, answer = len(nums), []
        # 더하는 세 수중 nums[i]가 가장 작은 수일 때의 경우의 수를 모두 구함
        for i in range(N):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            target = -1*nums[i]
            s, e = i + 1, N - 1
            while s < e:
                # nums[s] + nums[e] == target는 nums[i] + nums[s] + nums[e] == 0와 동일
                if nums[s] + nums[e] == target:
                    answer.append([nums[i], nums[s], nums[e]])
                    s = s + 1
                    while s < e and nums[s] == nums[s-1]:
                        s = s + 1
                elif nums[s] + nums[e] < target:
                    # 세 수의 합이 적으면 s(start) 지점을 올리고
                    s = s + 1
                else:
                    # 세 수의 합이 크면 e(end) 지점을 내린다
                    e = e - 1
        return answer

1. 중복을 피하기 위해 리스트를 정렬한 후 for문 내 while문을 통해 다음 수가 현재 비교중인 수와 다를 때까지 탐색하고 다시  루프를 실행한다.

2. 중복을 피하기 위해 앞쪽에서 비교하는 첫 요소(i번째 값)와 s(start)가 될 값이 다를 때까지 탐색한다.

 

문제의 힌트에 제시된대로 "two-sum" 문제로 풀어 해결할 수 있다. 그렇지 않고 단순하게 삼중루프를 돌린다면 time limit 제한에 걸린다.

 

 

 

728x90