LeetCode1:Two Sum

class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dict = {}
            for i in xrange(len(nums)):
                x = nums[i]
                if target-x in dict:
                    return (dict[target-x], i)
                dict[x] = i

注:
最精華的思想是:
x = nums[i] dict[x] = i
取出第i個數字(以0為開頭),把它的值裝載進dict中成為key,而原來的序號i變成了value
最終就能夠輕松的取出,value的值,即數列中的序號。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Given an array of integers, return indices of the two num...
    lemooon閱讀 271評論 0 0
  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • 文章作者:Tyan博客:noahsnail.com | CSDN | 簡書 1. 問題描述 Given an ar...
    SnailTyan閱讀 471評論 0 0
  • 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的...
    mztkenan閱讀 387評論 0 0
  • 問題:Given an array of integers, returnindicesof the two nu...
    Yinmu閱讀 214評論 0 0