勸學(xué)
孟郊〔唐代〕
擊石乃有火,不擊元無煙。
人學(xué)始知道,不學(xué)非自然。
萬事須己運,他得非我賢。
青春須早為,豈能長少年。
給定一個整數(shù)數(shù)組 nums 和一個整數(shù)目標(biāo)值 target,請你在該數(shù)組中找出 和為目標(biāo)值 target 的那 兩個 整數(shù),并返回它們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素在答案里不能重復(fù)出現(xiàn)。
你可以按任意順序返回答案。
示例 1:
輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
輸入:nums = [3,2,4], target = 6
輸出:[1,2]
示例 3:
輸入:nums = [3,3], target = 6
輸出:[0,1]
解答
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i, num in enumerate(nums):
remaining = target - num
if remaining in nums and i != nums.index(remaining):
return i, nums.index(remaining)
執(zhí)行用時:420 ms, 在所有 Python 提交中擊敗了51.10%的用戶
內(nèi)存消耗:12.9 MB, 在所有 Python 提交中擊敗了100.00%的用戶