Leetcode 1. Two Sum (Hashmap)

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the sameelement twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

這題不難,首先想到的就是暴力遍歷,用兩個for循環就能做出來,但是時間太長。時間複雜度爲O(n^2)。

 

後來也是看了其他人的解法,發現用HashMap的思想會比較快。最壞情況爲O(n)。

C++版:

 

Python版:

#Solution2
def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    n = len(nums)
    dic = {}
    for x in range(n):
        a = target - nums[x]
        if nums[x] in dic:          #關鍵步驟
            return dic[nums[x]], x
        else:
            dic[a] = x;

 

實例步驟如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章