題目描述:數組
給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。 你能夠假設每一個輸入只對應一種答案,且一樣的元素不能被重複利用。 示例: 給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
思路:每次遍歷一個元素,將元素添加到list中,並判斷(target-元素)是否在list中,若是在,獲取索引
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ list=[] if not nums: return list for num in nums: list.append(num) res=target-num if res in list: i=list.index(res) j=nums.index(num) return [i,j] return []