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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
我的答案: 基于python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # 这里是我的答案 for i inrange(len(nums)):
x = target - nums[i] nums.remove(nums[i]) if x in nums:
return [i, i+nums.index(x)+1]
略坑,上面的答案是错的。进行改进,但是感觉还是太复杂了一些。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import copy classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n = copy.deepcopy(nums) for i inrange(len(nums)):
x = target - n[i] nums.remove(n[i]) if x in nums:
return [i, i+nums.index(x)+1]
8月24号9:12再次改进,不使用deepcopy
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i inrange(len(nums)): x = target - nums[0] nums.remove(nums[0]) if x in nums: return [i, i + nums.index(x) + 1]