/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function (nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const diff = target - nums[i];
if (map.has(diff)) {
return [map.get(diff), i];
}
map.set(nums[i], i);
}
};
Go Code:
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, _ := range nums {
diff := target - nums[i]
if j, ok := m[diff]; ok {
return []int{i, j}
} else {
m[nums[i]] = i
}
}
return []int{}
}
CPP Code:
class Solution {
public:
vector<int> twoSum(vector<int>& A, int target) {
unordered_map<int, int> m;
for (int i = 0; i < A.size(); ++i) {
int t = target - A[i];
if (m.count(t)) return { m[t], i };
m[A[i]] = i;
}
return {};
}
};
Java Code:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
Python Code:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
复杂度分析
时间复杂度:$O(N)$
空间复杂度:$O(N)$
更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 40K star 啦。