• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

2周前 (04-07) 7次浏览

# 代码

``````pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut res:Vec<Vec<i32>> = Vec::new();
if nums.len() < 3 {
return res;
}
let mut nums2 = nums.clone();
nums2.sort_unstable();
if nums2[0] > 0 {
return res;
}
for i in 0..(nums2.len()-2) {
let mut target = -nums2[i];
if i > 0 && nums2[i] == nums2[i-1] {
continue;
}
let mut l = i+1;
let mut r = nums2.len()-1;
while l < r {
let mut temp = nums2[l] + nums2[r];
match temp.cmp(&target) {
std::cmp::Ordering::Equal => {
res.push(vec![-target,nums2[l],nums2[r]]);
while l < r && nums2[l] == nums2[l+1] {
l = l + 1;
}
while l < r && nums2[r] == nums2[r-1] {
r = r - 1;
}
l = l + 1;
r = r - 1;
},
std::cmp::Ordering::Less => {
l = l + 1
},
std::cmp::Ordering::Greater => {
r= r - 1
},
}
}
}
res
}
``````

# 测试

``````#[cfg(test)]
mod tests{
use super::*;
#[test]
fn test_1(){
assert_eq!(three_sum(vec![-1,0,1,2,-1,-4]),vec![vec![-1,-1,2],vec![-1,0,1]]);
}
#[test]
fn test_2(){
assert_eq!(three_sum(vec![]),vec![]);
}
#[test]
fn test_3(){
assert_eq!(three_sum(vec![0]),vec![]);
}
}
``````