forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.js
More file actions
86 lines (58 loc) · 2.23 KB
/
Jeehay28.js
File metadata and controls
86 lines (58 loc) · 2.23 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* @param {number[]} nums
* @return {number[][]}
*/
// Time Complexity: O(n^2)
// Space Complexity: O(n^2)
var threeSum = function (nums) {
const sorted = [...nums].sort((a, b) => a - b);
let result = [];
// Loop through the array and pick each number as the first number for the triplet
for (let i = 0; i < sorted.length - 2; i++) {
// skip duplicate values for sorted[middle]
if(i > 0 && sorted[i - 1] === sorted[i]) {
continue;
}
let left = i + 1; // Left pointer starts right after the current middle
let right = sorted.length - 1; // Right pointer starts at the last element
while (left < right) {
const sum = sorted[i] + sorted[left] + sorted[right];
if (sum === 0) {
result.push([sorted[left], sorted[i], sorted[right]]);
// skip duplicates for sorted[left] and sorted[right]
while(left < right && sorted[left] === sorted[left + 1]){
left += 1; // Move left pointer to the right to skip duplicate values
}
while(left < right && sorted[right] === sorted[right - 1]) {
right -= 1; // Move right pointer to the left to skip duplicate values
}
left += 1;
right -= 1;
} else if (sum > 0) {
right -= 1;
} else {
left += 1
}
}
}
return result;
};
// var threeSum = function (nums) {
// i != j, i != k, and j != k can be interpreted as i < j < k
// three nested loops
// time complexity of O(n³)
// Time Limit Exceeded
// let result = [];
// for (let i = 0; i < nums.length - 2; i++) {
// for (let j = i + 1; j < nums.length - 1; j++) {
// for (let k = j + 1; k < nums.length; k++) {
// if (nums[i] + nums[j] + nums[k] === 0) {
// const str = [nums[i], nums[j], nums[k]].sort((a, b) => a - b).join(",")
// result.push(str)
// }
// }
// }
// }
// result = [... new Set(result)].map(str => str.split(",").map(str => +str))
// return result;
// }