Skip to content

Commit 91c98c3

Browse files
committed
init
Signed-off-by: alei <[email protected]>
0 parents  commit 91c98c3

File tree

6 files changed

+76
-0
lines changed

6 files changed

+76
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
target/

Cargo.lock

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "leetcode-rust"
3+
version = "0.1.0"
4+
authors = ["alei <[email protected]>"]
5+
edition = "2019"
6+

README.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# My Leetcode Solution in Rust
2+
3+
Each `.rs` file consists of three parts:
4+
5+
* problem description
6+
* my solution
7+
* test cases
8+
9+
Run `cargo test test_{id}` to test the solution for problem #id.
10+
11+
Working in progress, solutions list:
12+
13+
* [1 - two sum](./src/two_sum_1.rs)

src/main.rs

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// make cargo happy
2+
pub mod two_sum_1;
3+
4+
fn main() {
5+
}

src/two_sum_1.rs

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* [1] Two Sum
3+
*
4+
* https://leetcode.com/problems/two-sum/description/
5+
*
6+
* Given an array of integers, return indices of the two numbers such that they
7+
* add up to a specific target.
8+
*
9+
* You may assume that each input would have exactly one solution, and you may
10+
* not use the same element twice.
11+
*
12+
* Example:
13+
*
14+
*
15+
* Given nums = [2, 7, 11, 15], target = 9,
16+
*
17+
* Because nums[0] + nums[1] = 2 + 7 = 9,
18+
* return [0, 1].
19+
*
20+
*/
21+
22+
pub struct Solution {}
23+
24+
use std::collections::HashMap;
25+
impl Solution {
26+
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
27+
let mut map = HashMap::with_capacity(nums.len());
28+
for (index, num) in nums.iter().enumerate() {
29+
match map.get(&(target - num)) {
30+
None => { map.insert(num, index); },
31+
Some(sub_index) => { return vec![*sub_index as i32, index as i32] },
32+
}
33+
}
34+
vec![]
35+
}
36+
}
37+
38+
#[cfg(test)]
39+
mod tests {
40+
use super::*;
41+
42+
#[test]
43+
fn test_1() {
44+
assert_eq!(vec![0, 1], Solution::two_sum(vec![2, 7, 11, 15], 9));
45+
assert_eq!(vec![1, 2], Solution::two_sum(vec![3, 2, 4], 6));
46+
}
47+
}

0 commit comments

Comments
 (0)