給定一個整數數列,找出其中和爲特定值的那兩個數。
你能夠假設每一個輸入都只會有一種答案,一樣的元素不能被重用。
示例:code
給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
#本身實現的方法:使用雙循環 class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i,n in enumerate(nums): for j,m in enumerate(nums): tar = n+m if tar ==target and i != j: return [i, j] #大牛的實現方法: def twoSum(self, nums, target): for i, num in enumerate(nums): sub_num = target - num if sub_num in nums: t_index = nums.index(sub_num) if t_index != i: return [i, t_index]