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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章