mirror of
https://github.com/rust-lang/rustlings.git
synced 2025-12-28 06:49:19 +00:00
feat(exercises): add LeetCode-style 'Two Sum' problem in new leetcode module
This commit is contained in:
parent
1955313362
commit
3c9f8f5f30
23
exercises/leetcode/two_sum.rs
Normal file
23
exercises/leetcode/two_sum.rs
Normal file
@ -0,0 +1,23 @@
|
||||
// TODO: Implement the "Two Sum" problem in Rust.
|
||||
// Given an array of integers `nums` and an integer `target`,
|
||||
// return the indices of the two numbers such that they add up to `target`.
|
||||
//
|
||||
// Hint: Try using a HashMap for O(n) time.
|
||||
// Remember ownership & borrowing rules for inserting into the map.
|
||||
|
||||
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
|
||||
// Your code here
|
||||
todo!()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_two_sum() {
|
||||
assert_eq!(two_sum(vec![2, 7, 11, 15], 9), vec![0, 1]);
|
||||
assert_eq!(two_sum(vec![3, 2, 4], 6), vec![1, 2]);
|
||||
assert_eq!(two_sum(vec![3, 3], 6), vec![0, 1]);
|
||||
}
|
||||
}
|
||||
@ -1209,3 +1209,8 @@ name = "as_ref_mut"
|
||||
dir = "23_conversions"
|
||||
hint = """
|
||||
Add `AsRef<str>` or `AsMut<u32>` as a trait bound to the functions."""
|
||||
|
||||
[[exercises]]
|
||||
name = "two_sum"
|
||||
dir = "leetcode"
|
||||
hint = "Use a HashMap to check if the complement exists."
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user