001-Two Sum

語言:python3


v1:輪詢

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]

結果:超時了,提交失敗

v2:建立字典,循環字典

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i in range(len(nums)):
            if not nums[i] in d:
                d[nums[i]] = i   #保存數組位置信息
            if target - nums[i] in d:
                if d[target - nums[i]] < i:  #防止 6-3=3的情況
                    return [d[target - nums[i]], i]

總結:字典映射結構比for循環效率更

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

推薦閱讀更多精彩內容

  • [TOC] P001 Two Sum Given an array of integers, return ind...
    hylexus閱讀 315評論 0 0
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,869評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,076評論 25 708
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優秀的...
    笨鳥慢飛閱讀 5,571評論 0 4
  • 先生出差了,朋友問去了哪里,我說吉林。長春?朋友說。我用了問號,但朋友確實是用肯定的語氣“說”的。 我不由想,如果...
    不是一棵蔥就是一瓣蒜閱讀 496評論 0 1