实例C++ Rust Python语言比较 1. 两数之和
提示
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n^2) 的算法吗?
C++: 8ms, 11MB mem
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (hash.count(complement)) {
return {hash[complement], i};
}
hash[nums[i]] = i;
}
return {};
}
};
Rust: 2ms, 2.4MB mem
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut hash = HashMap::new();
for (i, &num) in nums.iter().enumerate() {
let complement = target - num;
if let Some(&j) = hash.get(&complement) {
return vec![i as i32, j as i32]
} else {
hash.insert(num, i);
}
}
return vec![]
}
}
Java: 2ms, 43.75MB mem
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hash.containsKey(target - nums[i])) {
return new int[]{hash.get(target - nums[i]), i};
}
hash.put(nums[i], i);
}
return new int[0];
}
}
Golang: 4ms, 3.92MB mem
func twoSum(nums []int, target int) []int {
length := len(nums)
scanned_map := make(map[int]int, length)
for i, x := range nums {
if v, ok := scanned_map[target - x]; ok {
return []int{i, v}
} else {
scanned_map[x] = i
}
}
return nil
}
Python3: 36ms, 18.3MB mem
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_map = {}
for i in range(len(nums)):
num = nums[i]
j = num_map.get(target - nums[i])
if j is not None:
return [i, j]
else:
num_map[num] = i
return []