Skip to content
Closed
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
14 changes: 14 additions & 0 deletions contains-duplicate/livemehere.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use std::collections::HashSet;

impl Solution {
pub fn contains_duplicate(nums: Vec<i32>) -> bool {
let mut set: HashSet<i32> = HashSet::new();
for &n in nums.iter() {
if set.contains(&n) {
return true;
}
set.insert(n);
}
false
}
}
17 changes: 17 additions & 0 deletions two-sum/livemehere.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::collections::HashMap;

impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map: HashMap<i32, i32> = HashMap::new();

for (idx, &n) in nums.iter().enumerate() {
let pair = target - n;
if let Some(&pair_idx) = map.get(&pair) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 처음에 set으로 숫자 존재 여부만 체크했다가,
결국 배열을 다시 뒤져 인덱스를 찾아야 하는 불필요한 과정을 겪었어요.
HashMap + 가드 리턴 패턴을 보니, 앞쪽에서 바로 종료돼서 훨씬 효율적이네요!
배워갑니다 🙌

return vec![idx as i32, pair_idx];
} else {
map.insert(n, idx as i32);
}
}
vec![]
}
}