题目:https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked
Python3
解法1
这样我们创建一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
val2IdxDict = {}
for idx, val in enumerate(nums):
if target - val in val2IdxDict:
return [val2IdxDict[target - val], idx]
else:
val2IdxDict[val] = idx
return []
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
} else {
map.put(nums[i], i);
}
}
return new int[0];
}
}

被折叠的 条评论
为什么被折叠?



