#1
Easy Algorithms Two sum
Array Hash Table
57.1% acceptance
Feb 27, 2026
67856
2524
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map = std::collections::HashMap::new();
for (i, &num) in nums.iter().enumerate() {
let complement = target - num;
if let Some(&j) = map.get(&complement) {
return vec![j, i as i32];
}
map.insert(num, i as i32);
}
vec![]
}
}