給定一個(gè)整數(shù)數(shù)組和一個(gè)目標(biāo)值谆奥,找出數(shù)組中和為目標(biāo)值的兩個(gè)數(shù)哎榴。
你可以假設(shè)每個(gè)輸入只對(duì)應(yīng)一種答案琼蚯,且同樣的元素不能被重復(fù)利用蜕着。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lennum = len(nums)
for i in range(lennum):
for j in range(lennum):
if i != j:
if nums[i]+nums[j] == target:
return [i,j]
提交記錄
28 / 29 個(gè)通過(guò)測(cè)試用例
狀態(tài):超出時(shí)間限制
提交時(shí)間:0 分鐘之前
*** 修改代碼
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lennums = len(nums)
for i in range(lennums):
for j in range(i+1,lennums):
if nums[i] + nums[j] == target:
return([i,j])
image.png