728x90

15. 3Sum

정수 array nums 에서 세 정수의 합이 0 이되는 각기 다른 element 의 조합을 구하시오. (중복하는 조합은 제외)

 

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.

예시 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
 
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.
가능한 조합은 [-1,0,1] and [-1,-1,2].
elements 의 배열 순서는 고려하지 않아도 됨.

예시 2:

Input: nums = [0,1,1]
Output: []
세 element의 합이 0 되지 않는 경우 빈 array 를 return.

예시 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]

.

.

.

 

 

 

 

.

.

.

풀이

output=[]
nums.sort()

for i,n in enumerate(nums):
    if i>0 and nums[i-1]==n:
        continue
    start,end = i+1, len(nums)-1
    while start<end:

        ThreeSum=a+nums[start]+nums[end]
        if ThreeSum>0:
            end-=1
        elif ThreeSum<0:
            start+=1
        else:
            output.append([n,nums[start],nums[end]])
            start+=1
            while nums[start]==nums[start-1] and start<end:
                start+=1
return output

728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기