1.two_sum題目

題目

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 same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


思路

直觀思路是使用兩個for循環遍歷nums,然後if判斷。

class Solution(object):  
    def two_sum1(self, nums, target):  
        for i in range(0, len(nums)):  
            for j in range(i+1, len(nums)):  
                if((nums[i]+nums[j])==target):  
                    a = i  
                    b = j  
                    return[a, b]

Submit後AC,但是這種暴力搜索的時間複雜度較高。另一種更快速的方法是哈希法。

class Solution:  
    def twoSum(self, nums, target):  
        """ 
        :type nums: List[int] 
        :type target: int 
        :rtype: List[int] 
        """  
        d = {}  
        for i, j in enumerate(nums):  
            if target - j in d:  
                return(d[target-j], i)  
            else:  
                d[j] = i  

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