两数之和

  1. use std::collections::HashMap;
  2. use std::convert::TryInto;
  3. // Given an array of integers nums and an integer target,
  4. // return indices of the two numbers such that they add up to target.
  5. pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
  6. let mut hash_map: HashMap<i32, i32> = HashMap::new();
  7. for (i, item) in nums.iter().enumerate() {
  8. match hash_map.get(&(target - item)) {
  9. Some(value) => {
  10. return vec![i.try_into().unwrap(), *value];
  11. }
  12. None => {
  13. hash_map.insert(*item, i.try_into().unwrap());
  14. }
  15. }
  16. }
  17. vec![]
  18. }
  19. #[cfg(test)]
  20. mod test {
  21. use super::*;
  22. #[test]
  23. fn test() {
  24. let nums = vec![2, 7, 11, 15];
  25. assert_eq!(two_sum(nums, 9), vec![1, 0]);
  26. let nums = vec![3, 2, 4];
  27. assert_eq!(two_sum(nums, 6), vec![2, 1]);
  28. let nums = vec![3, 3];
  29. assert_eq!(two_sum(nums, 6), vec![1, 0]);
  30. }
  31. }