Skip to content

Commit 0af2879

Browse files
feat: 3sum 풀이
1 parent e219a99 commit 0af2879

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

3sum/grapefruitgreentealoe.js

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,42 @@ N^3 이상으로 보임.
6060
6161
*/
6262

63-
//2. 투포인터로 풀기
63+
//2. 투포인터로 풀기
64+
65+
/*
66+
우선 내가 문제에 대한 이해가 틀렸다. 숫자의 순서가 다르다고 하더라도, 같은 숫자의 조합을 가지고 있다면 안된다.
67+
값이 원하는 값보다 작으면 오른쪽 값을 옮기고, 크면 왼쪽 값을 옮기는 투포인터 전략을 취해보았다.
68+
69+
*/
70+
71+
/**
72+
* @param {number[]} nums
73+
* @return {number[][]}
74+
*/
75+
var threeSum = function(nums) {
76+
const triplets = []
77+
nums.sort((a,b)=>a-b)
78+
for(let i =0;i<nums.length -2 ;i++){
79+
if (i > 0 && nums[i] === nums[i - 1]) continue;
80+
let low = i+1
81+
,high = nums.length -1
82+
83+
while(low < high){
84+
const three_sum = nums[i] + nums[low] + nums[high]
85+
if(three_sum<0){
86+
low +=1
87+
}
88+
else if(three_sum >0){
89+
high -=1
90+
}
91+
else{
92+
triplets.push([nums[i],nums[low],nums[high]])
93+
while (low < high && nums[low] === nums[low + 1]) low++;
94+
while (low < high && nums[high] === nums[high - 1]) high--;
95+
low = low+1
96+
high = high -1
97+
}
98+
}
99+
}
100+
return triplets
101+
};

0 commit comments

Comments
 (0)