Skip to content

Commit e0715a4

Browse files
committed
week2 attempt 3
1 parent dfd89ee commit e0715a4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

โ€Ž3sum/Baekwangho.tsโ€Ž

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,37 @@ function threeSum(nums: number[]): number[][] {
110110
111111
๊ทผ๋ฐ ์–ด๋–ป๊ฒŒ๋“  ๋ชป๋งŒ๋“ฆ.
112112
*/
113+
114+
/**
115+
์–ด์ œ ํ•ด๋‹ต์„ ๋ณด์•˜์œผ๋‹ˆ, ๋‹ค์‹œํ•œ๋ฒˆ ํ’€์–ด๋ณด์ž.
116+
ํ•ต์‹ฌ์€ ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ, ์ž๋ฃŒ๊ตฌ์กฐ์— ์–ฝ๋ฉ”์ด์ง€ ์•Š๋Š” ๊ฒƒ
117+
*/
118+
119+
function threeSum(nums: number[]): number[][] {
120+
nums.sort((a, b) => a - b);
121+
const results = [];
122+
123+
// [-4, -1, -1, 0, 1, 2]
124+
for (let i = 0; i < nums.length; i++) {
125+
while (nums[i - 1] === nums[i]) i++;
126+
127+
let low = i + 1;
128+
let high = nums.length - 1;
129+
while (low < high) {
130+
const sum = nums[i] + nums[low] + nums[high];
131+
if (sum < 0) {
132+
low++;
133+
} else if (sum > 0) {
134+
high--;
135+
} else {
136+
while (nums[high] === nums[high - 1]) high--;
137+
while (nums[low] === nums[low + 1]) low++;
138+
results.push([nums[i], nums[low], nums[high]]);
139+
low++;
140+
high--;
141+
}
142+
}
143+
}
144+
145+
return results;
146+
}

0 commit comments

Comments
ย (0)