2019-11-25-Leetcode 兩數之和

所用語言:python

題目:給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的數組下標。

你可以假設每種輸入只會對應一個答案。但是,你不能重復利用這個數組中同樣的元素。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

來源:力扣(LeetCode)

鏈接:https://leetcode-cn.com/problems/two-sum

著作權歸領扣網絡所有。商業(yè)轉載請聯系官方授權,非商業(yè)轉載請注明出處。

解法1:使用兩個循環(huán)嵌套,逐個遍歷數組,將符合的條件記錄下來

class Solution(object):

? ? def twoSum(self, nums, target):

? ? ? ? """

? ? ? ? :type nums: List[int]

? ? ? ? :type target: int

? ? ? ? :rtype: List[int]

? ? ? ? """

? ? ? ? a=list()

? ? ? ? for i in range(len(nums)):

? ? ? ? ? ? for j in range(i+1,len(nums)):

? ? ? ? ? ? ? ? if nums[i]+nums[j]==target:

? ? ? ? ? ? ? ? ? ? return i,j

解法二:使用python中的‘in’條件語句:

class Solution(object):

? ? def twoSum(self, nums, target):

? ? ? ? """

? ? ? ? :type nums: List[int]

? ? ? ? :type target: int

? ? ? ? :rtype: List[int]

? ? ? ? """

? ? ? ? for i in range(len(nums)):

? ? ? ? ? ? a=target-nums[i]

? ? ? ? ? ? if a in nums and nums.index(a)!=i:

? ? ? ? ? ? ? ? return i,nums.index(a)


解法三,使用字典查找:

class?Solution(object):

????def?twoSum(self,?nums,?target):

????????"""

????????:type?nums:?List[int]

????????:type?target:?int

????????:rtype:?List[int]

????????"""

????????hashmap={}

????????for?i,num?in?enumerate(nums):

????????????#if?hashmap.get(target?-?num)?is?not?None:

????????????if?target-num?in?hashmap:

????????????????return?i,hashmap[target-num]

???????????????#?return?i,hashmap.get(target-num)

????????????hashmap[num]?=?i?#這句不能放在if語句之前,解決list中有重復值或target-num=num的情況


??????????????????????????????????? 解法一?????????????????? 解法二?????????????????? 解法三

?執(zhí)行用時|內存消耗??? 3852ms|12,5MB???? 976ms|12.4MB??? 28ms|13.1MB

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

相關閱讀更多精彩內容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 3,204評論 0 3
  • 15.三數之和 給定一個包含n個整數的數組nums,判斷nums中是否存在三個元素a,b,c ,使得a + b +...
    不愛去冒險的少年y閱讀 400評論 0 0
  • <center>#104 Maximum Depth of Binary Tree</center> link D...
    鐺鐺鐺clark閱讀 1,693評論 0 0
  • 今天去老姨和舅舅家上廟,請了兩個小時的假,都是老親戚了。 幾個姨姐妹都是一年見一次面,由于是長時間不見面,見面相互...
    悅如晨閱讀 173評論 0 4
  • 1 我和小影認識快二十年了,從上學到畢業(yè)再后來參加工作,一直到談婚論嫁,我們倆都幾乎形影不離,被窩一起鉆過無...
    舞月瓔閱讀 360評論 0 1

友情鏈接更多精彩內容