• 【Leetcode】 two sum #1 for rust solution


    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

     

    示例:

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    Rust Solution:

     1     pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
     2         let mut hashmap = HashMap::new();
     3         let mut vec: Vec<i32> = Vec::new();
     4         for (value1, &item ) in nums.iter().enumerate() {
     5             let temp = target - item;
     6             if let Some(&value2) = hashmap.get(&temp) {
     7                 vec.push(value2 as i32);
     8                 vec.push(value1 as i32);
     9             }
    10             hashmap.insert(item, value1);
    11         }
    12         vec
    13     }

    C++ Solution:

     1     vector<int> twoSum(vector<int>& nums, int target) {
     2         unordered_map<int, int> _map;
     3         for(int i = 0; i < nums.size(); i++)
     4         {
     5            int temp = target - nums[i];
     6            if(_map.find(temp) != _map.end()) {
     7                return { _map[temp], i};
     8            }
     9            _map[nums[i]] = i;
    10         }
    11         return {};
    12     }

    Python Solution:

    1 def twoSum(self, nums: List[int], target: int) -> List[int]:
    2         dict = {};
    3         for i in range(len(nums)):
    4             if (target - nums[i]) in dict :
    5                 return [dict[target - nums[i]], i]
    6             dict[nums[i]] = i

    Github link : https://github.com/DaviRain-Su/leetcode_solution/tree/master/two_sum

  • 相关阅读:
    归并排序算法
    交换排序算法
    插入排序算法
    DASCTF2021五月赛
    第二届newsctf
    山西省赛
    2021广东省第一届网络安全竞赛
    2021 DozerCTF
    2021-HSCTF re
    buuctf-re (持续更新)
  • 原文地址:https://www.cnblogs.com/Davirain/p/13521995.html
Copyright © 2020-2023  润新知