原题
https://leetcode.cn/problems/two-sum/
思路
用哈希表储存数字和下标
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 用字典储存数字和下标
seen = dict()
for i, n in enumerate(nums):
if target - n in seen:
return [i, seen[target-n]]
seen[n] = i
Java代码
class Solution {
public int[] twoSum(int[] nums, int target) {
// 用哈希表储存数字和下标
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (map.containsKey(target - n)) {
return new int[] {i, map.get(target - n)};
}
map.put(n, i);
}
return new int[2];
}
}