Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refine 3 sum #3

Merged
merged 2 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 0 additions & 46 deletions .vscode/launch.json

This file was deleted.

73 changes: 17 additions & 56 deletions three_sum/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,67 +1,28 @@
#![allow(dead_code)]

use std::collections::HashMap;

struct Solution {}

struct Extractor {
nums: Vec<i32>,
nums_map: HashMap<i32, usize>,
sums_map: HashMap<Vec<i32>, ()>,
}

impl Extractor {
fn new(nums: &Vec<i32>) -> Self {
let mut sorted_nums = nums.clone();
sorted_nums.sort();
let mut nums_map = HashMap::new();
for &n in nums.iter() {
let count = nums_map.entry(n).or_insert(0);
*count += 1;
}
Extractor {
nums: sorted_nums,
nums_map,
sums_map: HashMap::new(),
}
}

fn get_expected(&self, n: &i32, m: &i32) -> Option<i32> {
let exp = 0 - n - m;
let count = self.nums_map.get(&exp).unwrap_or(&0);
if vec![*n, *m, exp].iter().filter(|&x| *x == exp).count() > *count {
return None;
}
Some(exp)
}

fn build_sums_map(&mut self) {
for (i, n) in self.nums.iter().enumerate() {
'second_loop: for m in self.nums[i + 1..].iter() {
if let Some(exp) = self.get_expected(n, m) {
if exp < *m {
// wrong sort
break 'second_loop;
} else {
self.sums_map.insert(vec![*n, *m, exp], ());
impl Solution {
pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut sorted = nums.clone();
sorted.sort();
let mut sums = vec![];
for i in 0..sorted.len() {
let mut j = i + 1;
let mut k = sorted.len() - 1;
while j < k {
let group = vec![sorted[i], sorted[j], sorted[k]];
match group.iter().sum::<i32>() {
s if s < 0 => j += 1,
s if s > 0 => k -= 1,
_ => {
sums.push(group);
break;
}
} else {
continue 'second_loop;
}
}
}
}

fn three_sum(&mut self) -> Vec<Vec<i32>> {
self.build_sums_map();
self.sums_map.keys().cloned().collect()
}
}

impl Solution {
pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut ext = Extractor::new(&nums);
ext.three_sum()
sums
}
}

Expand Down