15. 3Sum Python3

Yelim Kim·2021년 9월 16일
0
post-thumbnail

Problem

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]]

Example 2:

Input: nums = []
Output: []

Example 3:

Input: nums = [0]
Output: []

Constraints:

0 <= nums.length <= 3000
-105 <= nums[i] <= 105

My code

class Solution:
    def threeSum(self, nums: list[int]) -> list[list[int]]:
        count = defaultdict(int)
        positives: set[int] = set()
        negatives: set[int] = set()
        for n in nums:
            count[n] += 1
            if n >= 0:
                positives.add(n)
            elif n < 0:
                negatives.add(n)
        triplets: list[list[int]] = []
        if count[0] >= 3:
            triplets.append([0, 0, 0])
        for x in positives:
            for y in negatives:
                z: int = -x - y
                if count[z] == 0:
                    continue
                if (z == x or z == y) and count[z] < 2:
                    continue
                if z < y or z > x:
                    continue
                triplets.append([y, z, x])
        return triplets

Review

[실행 결과]
Runtime: 667 ms / Memory: 36.2MB

[접근법]
two sum을 응용해서 해보려고 했으나 실패. 결국 조건을 많이 세분화하기로 했음 -> 런타임이 줄어듬 결국 이득(?
양수와 음수로 나눈 다음 각각 하나씩 뽑은 후 0에서 그 수를 뺀 수가 존재하면 출력(후 순환), 아니면 다시 순환
뺀 수가 없거나, 양수나 음수와 겹치는 수거나, 합이 0이 되지 않을때 조건을 걸었음
3차원 리스트 사용하여 출력

[느낀점]
코드가 길어지는 걸 두려워하지 말자... 제발 일찍 포기 no
답이 숫자 세개씩 출력하는 문제라면 삼차원 리스트를 생각해볼 것

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글