Python 兩數(shù)之和

兩數(shù)之和

給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會(huì)對應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。

示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

1、

class Solution:
    def twoSum(self, nums: List[int], target: int):
        for i in nums:
            j = target - i
            start_index = nums.index(i)
            next_index = start_index + 1
            temp_num = nums[next_index:]
            if j in temp_num:
                return [nums.index(i), next_index + temp_num.index(j)]

2、

class Solution(object):
    def twoSum(self, nums, target):
        # 定義字典
        num_dict = {}
        len_nums = len(nums)
        # 遍歷列表
        for i in range(len_nums):
            temp = target - nums[i]
            if temp not in num_dict:
                num_dict[nums[i]] = i
            else:
                return [num_dict[temp], i]

我不生產(chǎn)程序,我只是程序的搬運(yùn)工

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容