본문 바로가기
python-algorithm

leetcode 15. 3Sum

by 무적김두칠 2023. 2. 9.

https://leetcode.com/problems/3sum/description/

 

3Sum - LeetCode

3Sum - 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

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        answer = []
        nums.sort()
 
        for i in range(len(nums)-2):
            if i>0 and nums[i] == nums[i-1]:
                continue
            
            left, right = i + 1len(nums) - 1
 
            while left < right:
                sum = nums[i]+ nums[left]+nums[right]
 
                if sum<0:
                    left+=1
                elif sum>0:
                    right-=1
                else:
                    answer.append([nums[i], nums[left], nums[right]])
 
                    while left< right and nums[left] == nums[left+1]:
                        left+=1
                    while left< right and nums[right] == nums[right-1]:
                        right -=1
                    
                    left +=1
                    right -=1
        
        return answer
cs
반응형

'python-algorithm' 카테고리의 다른 글

leetcode 2149. Rearrange Array Elements by Sign  (0) 2023.02.10
leetcode 238. Product of Array Except Self  (0) 2023.02.10
leetcode 42. Trapping Rain Water  (0) 2023.02.09
백준 27389 Metronome  (0) 2023.02.09
백준 27434 팩토리얼 3  (0) 2023.02.09

댓글