Implemented problem 15
This commit is contained in:
parent
3e15c5bd78
commit
c9e582b553
1 changed files with 17 additions and 11 deletions
|
@ -1,26 +1,32 @@
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("{:?}", three_sum(vec![-1,0,1,2,-1,-4]));
|
println!("{:?}", three_sum(vec![-1,0,1,2,-1,-4]));
|
||||||
|
println!("{:?}", three_sum(vec![0,0,0,0,0,0]));
|
||||||
|
println!("{:?}", three_sum(vec![-2,0,0,2,2]));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: fix and optimize
|
// TODO: fix and optimize
|
||||||
pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
|
pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
|
||||||
let mut result: Vec<Vec<i32>> = Vec::new();
|
let mut result = Vec::<Vec<i32>>::new();
|
||||||
let mut seen = std::collections::HashSet::<i32>::with_capacity(nums.len());
|
|
||||||
let mut seen2 = std::collections::HashSet::<i32>::with_capacity(nums.len()-1);
|
|
||||||
nums.sort();
|
nums.sort();
|
||||||
for i in 0..nums.len()-2 {
|
for i in 0..nums.len()-2 {
|
||||||
if seen.contains(&nums[i]) { continue; }
|
if i > 0 && nums[i] == nums[i - 1] { continue; }
|
||||||
for j in i+1..nums.len()-1 {
|
let (mut j, mut k) = (i + 1, nums.len() - 1);
|
||||||
if seen2.contains(&nums[j]) { continue; }
|
while j < k {
|
||||||
for k in j+1..nums.len() {
|
if j > i + 1 && nums[j - 1] == nums[j] {
|
||||||
if nums[i] + nums[j] + nums[k] == 0 {
|
j += 1; continue;
|
||||||
|
}
|
||||||
|
if k < nums.len() - 1 && nums[k + 1] == nums[k] {
|
||||||
|
k -= 1; continue;
|
||||||
|
}
|
||||||
|
match (nums[i] + nums[j] + nums[k]).cmp(&0) {
|
||||||
|
std::cmp::Ordering::Less => { j += 1; },
|
||||||
|
std::cmp::Ordering::Greater => { k -= 1 },
|
||||||
|
std::cmp::Ordering::Equal => {
|
||||||
result.push(vec![nums[i], nums[j], nums[k]]);
|
result.push(vec![nums[i], nums[j], nums[k]]);
|
||||||
|
j += 1; k -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
seen2.insert(nums[j]);
|
|
||||||
}
|
}
|
||||||
seen.insert(nums[i]);
|
|
||||||
seen2.clear();
|
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue