[Leetcode] 15. 3Sum

mydailylogs
|2023. 5. 1. 13:20
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        answer = set()

        n, p, z = [], [], []
        for num in nums:
            if num > 0:
                p.append(num)
            elif num < 0:
                n.append(num)
            else:
                z.append(num)

        N, P = set(n), set(p)
        if z:
            for num in P:
                if -1 * num in N:
                    answer.add(( -1 *num, 0, num ))
        
        if len(z) >= 3:
            answer.add((0, 0, 0))
        
        for i in range(len(n)):
            for j in range(i+1, len(n)):
                target = -1 * (n[i] + n[j])
                if target in P:
                    answer.add(tuple(sorted([n[i], n[j], target])))

        for i in range(len(p)):
            for j in range(i+1, len(p)):
                target = -1 * (p[i] + p[j])
                if target in N:
                    answer.add(tuple(sorted([target, p[i], p[j]])))
        
        return answer

'CS > 알고리즘' 카테고리의 다른 글

[Leetcode] 17. Letter Combinations of a Phone Number  (0) 2023.05.01
[Leetcode] 16. 3Sum Closest  (0) 2023.05.01
[Leetcode] 1. Two Sum  (0) 2023.05.01
[Leetcode] 12. Integer to Roman  (0) 2023.05.01
[Leetcode] 202. Happy Number  (0) 2023.04.27