๐Ÿง  3Sum

๋ฌธ์ œ

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

  • The solution set must not contain duplicate triplets.

๋‚˜์˜ ํ’€์ด

def threeSum(self, nums: List[int]) -> List[List[int]]:
    nums = sorted(nums)
    res = []
    if len(nums) < 3:
        return res
    for i in range(len(nums)):
        needs = 0 - nums[i]
        for j in range(i+1, len(nums)):
            need = needs - nums[j]
            tmp_nums = nums[:]
            tmp_nums.remove(nums[i])
            tmp_nums.remove(nums[j])
            if need in tmp_nums:
                answer = [nums[i], nums[j], need]
                if sorted(answer) not in res:
                    res.append(answer)
    return res

์ฃผ์–ด์ง„ ๋ฐฐ์—ด nums์—์„œ ๋”ํ•˜๋ฉด 0์ด ๋˜๋Š” 3๊ฐœ์˜ ์ˆซ์ž set์„ ๊ตฌํ•˜์—ฌ ๋ฆฌํ„ดํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

๋‚˜๋Š” ์šฐ์„  nums๋ฅผ ์ •๋ ฌ์‹œํ‚จ ๋‹ค์Œ for๋ฌธ์„ ๋Œ๋ฉฐ i๊ฐ€ 0์ด ๋˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ๋‘ ์ˆ˜๋ฅผ ์ฐพ์•„๋‚ด๋ฉด answer์— ๋”ํ•˜๋Š” ์‹์œผ๋กœ ํ•ด๊ฒฐํ–ˆ๋Š”๋ฐ ๊ฒฐ๊ตญ Time Limit์— ๊ฑธ๋ ธ๋‹ค. ์–ด์ฐŒ๋ณด๋ฉด ๋‹น์—ฐํ•œ๊ฒŒ ์ •๋ ฌ ํ›„ ์ด์ค‘ for๋ฌธ์—์„œ if๋ฌธ์œผ๋กœ tmp_nums๋ฅผ ๋˜ ํƒ์ƒ‰ํ•˜๋Š” ์ฝ”๋“œ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋Š๋ฆด ์ˆ˜๋ฐ–์— ์—†์—ˆ๋‹ค.

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

def threeSum(self, nums: List[int]) -> List[List[int]]:
    res = []
    nums.sort()
    length = len(nums)
    
    for i in range(length-2):
        if nums[i] > 0:
            break
        if i > 0 and nums[i] == nums[i-1]:
            continue
        l, r = i + 1, length - 1
        while l < r:
            total = nums[i] + nums[l] + nums[r]
            if total < 0:
                l += 1
            elif total > 0:
                r -= 1
            else:
                res.append([nums[i], nums[l], nums[r]])
                while l < r and nums[l] == nums[l+1]:
                    l += 1
                while l < r and nums[r] == nums[r-1]:
                    r -= 1
                l += 1
                r -= 1
    return res

์ด ๋ถ„์€ ์šฐ์„  ์ •๋ ฌํ•œ ๋ฐฐ์—ด์˜ ์ฒซ๋ฒˆ์งธ ๊ฐ’์ด ์–‘์ˆ˜์ธ ๊ฒฝ์šฐ ๋ฐ”๋กœ ๋ฆฌํ„ดํ–ˆ๋‹ค. ์Œ์ˆ˜๊ฐ€ ์—†์œผ๋ฉด ์•„๋ฌด๋ฆฌ ์กฐํ•ฉํ•ด๋„ 0์„ ๋งŒ๋“ค ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋‹ค์Œ์œผ๋กœ ํ˜„์žฌ ๊ฐ’๊ณผ ๋ฐ”๋กœ ์ „ ๊ฐ’์ด ๋™์ผํ•˜๋ฉด ์ง€๋‚˜์นœ๋‹ค.

ํ˜„์žฌ ์ธ๋ฑ์Šค์— 1์„ ๋”ํ•œ ๊ฐ’์„ l, ์ด ๊ธธ์ด์—์„œ 1์„ ๋บ€ ๊ฐ’(=๋ฐฐ์—ด์˜ ์ด ์ธ๋ฑ์Šค)์„ r์— ์ €์žฅํ•œ๋‹ค. l์ด r๋ณด๋‹ค ์ž‘์€ ๋™์•ˆ while๋ฌธ์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

๋ฐฐ์—ด์˜ ํ˜„์žฌ ๊ฐ’๊ณผ ๋‹ค์Œ ๊ฐ’, ๋งˆ์ง€๋ง‰ ๊ฐ’์„ ๋”ํ•˜์—ฌ total์— ์ €์žฅํ•˜๊ณ  ๊ทธ ๊ฐ’์ด ์Œ์ˆ˜์ธ ๊ฒฝ์šฐ l์„ ์ฆ๊ฐ€์‹œํ‚ค๊ณ  ์–‘์ˆ˜์ธ ๊ฒฝ์šฐ r์„ ๊ฐ์†Œ์‹œํ‚จ๋‹ค. ์„ธ ๊ฐœ์˜ ํ•ฉ์ด 0์ธ ๊ฒฝ์šฐ ๊ฒฐ๊ณผ๊ฐ’์— ์ถ”๊ฐ€ํ•˜๊ณ  l๊ฐ’๊ณผ r๊ฐ’์„ ์กฐ์ •ํ•œ๋‹ค.

๋‚˜๋จธ์ง€ ๋‘ ์ˆซ์ž๋ฅผ ๋ฌด์ž‘์ • ๊ฐ™์€ ๋ฐฐ์—ด์˜ for๋ฌธ์œผ๋กœ ๋Œ์ง€ ์•Š๊ณ  ์ดˆ๊ธฐํ™”ํ•œ ํ›„ ์ธ๋ฑ์Šค๋ฅผ ์กฐ์ ˆํ•˜๋ฉฐ ์ฐพ์•„๊ฐ€๋‹ˆ ํ›จ์”ฌ ๋น ๋ฅด๋‹ค.

References


Written by@ugaemi
Record things I want to remember

๐Ÿฑ GitHub๐Ÿ“š Reading Space