python3
# 解法一:暴力解法 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: result = [] for i in range(len(nums)): for j in range(i+1, len(nums)): if target == nums[i] + nums[j]: result.append(i) result.append(j) return result # 解法二:哈希map class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: result = {} for index, value in enumerate(nums): if result.get(target-value) is not None: return [index, result.get(target-value)] result[value] = index return result # 注:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
Go
解法一: func twoSum(nums []int, target int) []int { for i := 0;i<len(nums);i++ { for j:=i+1;j<len(nums);j++ { if target == nums[i] + nums[j] { return []int{i,j} } } } return nil } 时间复杂度:O(N^2) 解法二: func twoSum(nums []int, target int) []int { hashmap := map[int]int{} for index, value := range nums { if p, ok := hashmap[target-value]; ok { return []int{index,p} } hashmap[value] = index } return nil }