Skip to content

Commit e89acb1

Browse files
authored
3sum (#2675)
1 parent 4b99484 commit e89acb1

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

3sum/DaleSeo.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// TC: O(n^2)
2+
// SC: O(1)
3+
impl Solution {
4+
pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
5+
nums.sort_unstable();
6+
let n = nums.len();
7+
let mut triplets = Vec::new();
8+
9+
for i in 0..n {
10+
if i > 0 && nums[i] == nums[i - 1] {
11+
continue;
12+
}
13+
14+
let (mut low, mut high) = (i + 1, n - 1);
15+
while low < high {
16+
let three_sum = nums[i] + nums[low] + nums[high];
17+
if three_sum < 0 {
18+
low += 1;
19+
} else if three_sum > 0 {
20+
high -= 1;
21+
} else {
22+
triplets.push(vec![nums[i], nums[low], nums[high]]);
23+
low += 1;
24+
high -= 1;
25+
while low < high && nums[low] == nums[low - 1] {
26+
low += 1;
27+
}
28+
while low < high && nums[high] == nums[high + 1] {
29+
high -= 1;
30+
}
31+
}
32+
}
33+
}
34+
35+
triplets
36+
}
37+
}

0 commit comments

Comments
 (0)