-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0015-3sum.rs
61 lines (31 loc) · 1.11 KB
/
0015-3sum.rs
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
use std::cmp::Ordering::{Equal, Greater, Less};
impl Solution {
pub fn three_sum(mut numbers: Vec<i32>) -> Vec<Vec<i32>> {
numbers.sort_unstable();
let mut ans: Vec<Vec<i32>> = Vec::new();
for i in 0..numbers.len() {
if i > 0 && numbers[i] == numbers[i - 1] {
continue;
}
let (mut l, mut r) = (i + 1, numbers.len() - 1);
while l < r {
match (numbers[i] + numbers[l] + numbers[r]).cmp(&0) {
Less => l += 1,
Greater => r -= 1,
Equal => {
ans.push(vec![numbers[i], numbers[l], numbers[r]]);
l += 1;
while numbers[l] == numbers[l - 1] && l < r {
l += 1;
}
r -= 1;
while numbers[r] == numbers[r + 1] && l < r {
r -= 1;
}
}
}
}
}
ans
}
}