Created
February 5, 2020 02:25
-
-
Save ByungSunBae/ced8ebfac1a9b2f6080eadaea9c2cee7 to your computer and use it in GitHub Desktop.
Two Sum problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From : https://leetcode.com/problems/two-sum | |
pub struct Inputs { | |
pub nums: Vec<i32>, | |
pub target: i32, | |
} | |
pub trait Solution { | |
fn two_sum(&self) -> Vec<i32>; | |
fn result_solution(&self) -> String { | |
format!("{:?}", self.two_sum()) | |
} | |
} | |
fn find_position(nums: &Vec<i32>, target: &i32) -> Vec<i32> { | |
let mut res = Vec::new(); | |
for (i, &num) in nums.iter().enumerate() { | |
if num == *target{ | |
res.push(i as i32) | |
} | |
} | |
return res | |
} | |
impl Solution for Inputs { | |
fn two_sum(&self) -> Vec<i32> { | |
//let mut idx: i32 = 0; | |
let mut res: Vec<i32> = Vec::new(); | |
//let mut iters = self.nums.iter().enumerate(); | |
for &num in self.nums.iter() { | |
let diff = self.target - num; | |
res = Vec::new(); | |
println!("Diff {}", diff); | |
if diff == num { | |
let idx_vec1 = find_position(&self.nums, &diff); | |
if idx_vec1.len() != 0 && idx_vec1.len() > 1 { | |
res.push(idx_vec1[0]); | |
res.push(idx_vec1[1]); | |
} | |
} else { | |
let idx_vec1 = find_position(&self.nums, &diff); | |
let idx_vec2 = find_position(&self.nums, &num); | |
res.push(idx_vec1[0]); | |
res.push(idx_vec2[0]); | |
} | |
if res.len() == 2 { | |
break | |
} | |
} | |
assert_eq!(res.len(), 2); | |
return res | |
} | |
} | |
fn main() { | |
let inputs = Inputs { | |
nums: vec![3, 2, 4], | |
target:6, | |
}; | |
println!("{}", inputs.result_solution()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment