Day 1
题目:两数之和
leetcode链接:两数之和
要点:哈希表
1、Java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashmap = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if (hashmap.containsKey(target - nums[i])){
return new int[]{hashmap.get(target - nums[i]), i};
}
hashmap.put(nums[i], i);
}
return new int[0];
}
}
2、Python
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[num] = i
return []