Skip to content

Commit 653d316

Browse files
committed
add solution for two_sum
0 parents  commit 653d316

File tree

4 files changed

+90
-0
lines changed

4 files changed

+90
-0
lines changed

Diff for: .gitignore

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
### Example user template template
3+
### Example user template
4+
5+
# IntelliJ project files
6+
.idea
7+
*.iml
8+
out
9+
gen### Rust template
10+
# Generated by Cargo
11+
# will have compiled files and executables
12+
/target/
13+
14+
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
15+
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
16+
Cargo.lock
17+
18+
# These are backup files generated by rustfmt
19+
**/*.rs.bk
20+
21+
22+
23+
#Added by cargo
24+
#
25+
#already existing elements are commented out
26+
27+
/target
28+
#**/*.rs.bk

Diff for: Cargo.toml

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

Diff for: src/lc-001.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
use std::collections::HashMap;
2+
3+
impl Solution {
4+
5+
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
6+
7+
let mut rs: Vec<i32> = Vec::new();
8+
for i in 0..nums.len() {
9+
for j in i +1 .. nums.len() {
10+
if nums[i] + nums[j] == target {
11+
rs.push(i as i32);
12+
rs.push(j as i32);
13+
return rs
14+
}
15+
}
16+
}
17+
return rs;
18+
}
19+
20+
// the second solution
21+
pub fn two_sum_s2(nums: Vec<i32>, target: i32) -> Vec<i32> {
22+
23+
let mut i1 :i32 = 0;
24+
let mut i2 = 0;
25+
let mut m: HashMap<i32, i32> = HashMap::new();
26+
27+
for i in 0.. nums.len() {
28+
let sub = target - &nums[i];
29+
if m.contains_key(&sub){
30+
i1 = i as i32;
31+
i2 = *m.get(&sub).unwrap();
32+
break;
33+
}else {
34+
m.insert(nums[i], i as i32);
35+
}
36+
}
37+
38+
if i1 < i2 {
39+
return vec![i1, i2];
40+
}else {
41+
return vec![i2, i1];
42+
}
43+
}
44+
}

Diff for: src/main.rs

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
use std::fs::read;
3+
4+
fn main() {
5+
println!("Hello, world!");
6+
7+
// let tnums = vec![2, 3, 4, 5];
8+
// let x = two_sum_s2(tnums, 5);
9+
//
10+
// println!("the index is {:?}", x)
11+
}

0 commit comments

Comments
 (0)