-
Notifications
You must be signed in to change notification settings - Fork 0
/
15.三数之和.rs
66 lines (61 loc) · 1.85 KB
/
15.三数之和.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
62
63
64
65
/*
* @lc app=leetcode.cn id=15 lang=rust
*
* [15] 三数之和
*/
// -2 -1 0 1 2 3
// @lc code=start
impl Solution {
pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut result = Vec::new();
if nums.len() < 3 {
return result;
}
nums.sort();
for idx in 0..(nums.len() - 2) {
if idx > 0 && nums[idx] == nums[idx - 1] {
continue;
}
let mut head = idx + 1;
let mut tail = nums.len() - 1;
while head < tail {
let sum = nums[idx] + nums[head] + nums[tail];
if sum == 0 {
result.push(vec![nums[idx], nums[head], nums[tail]]);
head += 1;
while head < nums.len() && nums[head] == nums[head - 1] {
head += 1;
}
if head >= nums.len() {
break;
}
tail -= 1;
while tail > idx && nums[tail] == nums[tail + 1] {
tail -= 1;
}
if tail <= idx {
break;
}
} else if sum < 0 {
head += 1;
while head < nums.len() && nums[head] == nums[head - 1] {
head += 1;
}
if head >= nums.len() {
break;
}
} else {
tail -= 1;
while tail > idx && nums[tail] == nums[tail + 1] {
tail -= 1;
}
if tail <= idx {
break;
}
}
}
}
return result;
}
}
// @lc code=end