Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
func(nums []int, target int) []int { m1 := make(map[int]int) for index, value := range nums { m1[value] = index } for index, value := range nums { complement := target - value if v, ok := m1[complement]; ok { if m1[complement] != index { return []int{index, v} } } } return []int{} }
python实现
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): def(self, nums, target): result = [] data = {} for i in range(len(nums)): if (target - nums[i]) in data.keys(): result.append(data.get(target - nums[i])+1) result.append(i+1) else: data[nums[i]] = i return result
近期评论