1. Two Sum Easy

@problem@discussion
#Array#Hash Table


This is a test explanation for a leetcode solution.

2 sum

damn


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


Back
© 2025 bowen.ge All Rights Reserved.