add initial data
This commit is contained in:
1 parent
048a82b101
commit
51d935d06b
66 files changed
+1329
No files matched your search
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "two-sum"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "two-sum"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,45 @@
|
||||
struct Solution;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
impl Solution {
|
||||
pub fn two_sum_o_n(nums: Vec<i32>, target: i32) -> Vec<i32> {
|
||||
// value -> idx map
|
||||
let mut map: HashMap<i32, usize> = HashMap::with_capacity(nums.len());
|
||||
|
||||
for (idx, num) in nums.iter().enumerate() {
|
||||
let diff = target - *num;
|
||||
if let Some(idx2) = map.get(&diff) {
|
||||
return vec![idx as _, *idx2 as _];
|
||||
}
|
||||
map.insert(*num, idx);
|
||||
}
|
||||
|
||||
unreachable!("we are guaranteed an answer exists")
|
||||
}
|
||||
|
||||
pub fn two_sum_o_n_log_n(nums: Vec<i32>, target: i32) -> Vec<i32> {
|
||||
let mut indexed_nums: Vec<_> = nums.into_iter().enumerate().collect();
|
||||
indexed_nums.sort_unstable_by_key(|(_, val)| *val);
|
||||
|
||||
let mut left = 0;
|
||||
let mut right = indexed_nums.len() - 1;
|
||||
|
||||
while left < right {
|
||||
let sum = indexed_nums[left].1 + indexed_nums[right].1;
|
||||
if sum == target {
|
||||
return vec![indexed_nums[left].0 as _, indexed_nums[right].0 as _];
|
||||
} else if sum > target {
|
||||
right -= 1;
|
||||
} else {
|
||||
left += 1;
|
||||
}
|
||||
}
|
||||
|
||||
unreachable!("we are guaranteed a solution exists")
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
Reference in new issue
Block a user