LeetCode:Two Sum

這是第一題的python代碼,思路是將輸入映射成爲一個map,數組元素的值爲key,下標爲value,然後直接去map中查找target減去每一個元素之後的值,在map中找到key對應的value以及剛纔的那個索引就是返回結果。這種解法的時間複雜度只有O(N)。

突然發現python因爲有很多現成的高級數據結構,寫起算法來真方便。


    #! /usr/bin/env python
    """
    leetcode first, two num
    """

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: list[int]
            :type target: int
            :rtype: list[int]
            """

            ret = []
            dict = {}
            for i in range(0, len(nums)):
                dict[nums[i]] = i
            for i in range(0, len(nums)):
                other = target - nums[i]
                if dict.has_key(other) and dict[other] != i:
                    ret.append(i)
                    ret.append(dict[other])
                    return ret

            return []

    if __name__ == "__main__":
        s = Solution()
        nums = [2, 7, 11, 15]
        target = 22
        ret = s.twoSum(nums, target)
        for i in range(0, len(ret)):
            print ret[i]
發佈了24 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章