1. Two Sum #
题目 #
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]
代码 #
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut numbers: HashMap<i32, i32> = HashMap::new();
for (idx, value) in nums.iter().enumerate() {
match numbers.get(&(target - value)) {
Some(pre_idx) => {
return vec![i32::from(*pre_idx), idx as i32];
},
None => {
numbers.insert(i32::from(*value), idx as i32);
}
}
}
return vec![];
}
}