leetcode 18 rust
题目
编程语言
rust
注意点
同leetcode15
代码
pub fn four_sum(nums: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let mut res : Vec<Vec<i32>> = Vec::new();
if nums.len() < 4 {
return res;
}
let mut nums2 = nums.clone();
nums2.sort();
if nums2[0] > 0 {
return res;
}
for i in 0..(nums2.len()-3) {
if i > 0 && nums2[i] == nums2[i-1] {
continue;
}
for j in (i+1)..(nums2.len()-2) {
if j > i+1 && nums2[j] == nums2[j-1] {
continue;
}
let mut l = j+1;
let mut r = nums2.len()-1;
while l < r {
let sum = nums2[i] + nums2[j] + nums2[l] + nums2[r];
match sum.cmp(&target) {
std::cmp::Ordering::Equal => {
res.push(vec![nums2[i],nums2[j],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!(four_sum(vec![1,0,-1,0,-2,2],0),vec![vec![-2,-1,1,2],vec![-2,0,0,2],vec![-1,0,0,1]]);
}
#[test]
fn test_2(){
assert_eq!(four_sum(vec![],0),Vec::<Vec<i32>>::new());
}
}
posted on 2021-04-08 10:16 GeniusOfCX 阅读(45) 评论(0) 编辑 收藏 举报