3sum

치킨치·2024년 6월 3일
0

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.

삼중 for문으로 처음 시도했지만 tese case에 timeout이 발생했다.
역시 삼중 for문은 문제가 되는구나.
for와 while을 섞고, while 내부에서 left right를 교차시키는 방법으로 loop를 하나 없앴다.

중복이 나오지 않아야하므로 Set<[Int]>에 저장하여 값을 유일하게 유지시켰다.
nums[left]==nums[left+1] 일때 left+=1를 해주는 방법도 있겠지만, Set이 O(1)이므로 연산속도에 큰 영향이 없을 것 같아서 코드를 유지했다.
아래는 풀이에 사용한 코드이다:

class Solution {
    func threeSum(_ nums: [Int]) -> [[Int]] {
        var results = Set<[Int]>()
        
        var nums = nums.sorted()
        for i in 0..<nums.count-2 {
            var left = i+1
            var right = nums.count-1
            while left < right {
                if nums[i] + nums[left] + nums[right] == 0 {
                    results.insert([nums[i], nums[left], nums[right]])
                    left += 1
                    right -= 1
                } else if nums[i] + nums[left] + nums[right] < 0 {
                    left += 1
                } else {
                    right -= 1
                }
            }
        }
        
        return .init(results)
    }
}
profile
풀스텍이었던 iOS개발자

0개의 댓글