forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhigeuni.js
43 lines (36 loc) ยท 1.24 KB
/
higeuni.js
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
31
32
33
34
35
36
37
38
39
40
41
42
// complexity
// time: O(n^2)
// - sort: O(n log n)
// - for loop: O(n)
// - while loop: O(n)
// space: O(n)
// - sortedNums: O(n)
// - else : O(1)
var threeSum = function(nums) {
const sortedNums = nums.sort((a, b) => a - b)
const lengthOfArray = nums.length;
const answer = [];
for(let i = 0; i < lengthOfArray; i++ ) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
const target = (-1) * sortedNums[i];
let left = i + 1;
let right = lengthOfArray - 1;
while(left < right) {
const sumOfLeftAndRight = sortedNums[left] + sortedNums[right];
const diff = sumOfLeftAndRight - target;
if( diff > 0 ){
right -= 1;
} else if ( diff < 0 ){
left += 1
} else {
answer.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
// ์ค๋ณต๋๋ ๋ถ๋ถ์ ์ฒ๋ฆฌํ๋ ๊ณผ์ ์์ ๊ณ์ fail๋์ด ์ฐพ์๋ณด๋ ์ด๋ ๊ฒ ํด์ผ ํต๊ณผ๋์๋ค.
while(left < right && sortedNums[left] === sortedNums[left + 1]) left ++;
while(left < right && sortedNums[right] === sortedNums[right - 1]) right --;
left++;
right--;
}
}
}
return answer
};