LeetCode 1. Two Sum Python Solution

此題目對應於 LeetCode 1

此題目對應於1. 兩數之和

題目要求:

 

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.

給一個數組和一個數值,數組中有兩個元素的和等於給定數值,求該兩個元素在原數組中對應下標

這裏我提供2個解法

解法1:粗暴解法,時間O(n^2),LeetCode運行時間 4945 ms

 

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums)<2:
            return None
        if len(nums)==2:
            return [0,1]
        for i in range(len(nums)):
            left = nums[i]
            for j in range(i+1,len(nums)):
                right = nums[j]
                if left+right == target:
                    return [i,j]

 

解法2:採取輔助的dict數據結構,只需進行一次遍歷,時間O(n),LeetCode運行時間 35ms

值得注意的是判斷某個key是否存在於dict中的時間複雜度是O(1)的,dict採用了hash的算法。

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums)<2:
            return None
        if len(nums)==2:
            return [0,1]
        dic = {}#key:target-num,補數,value:補數所在的位置
        for i in range(len(nums)):
            if nums[i] in dic:
                return [dic[nums[i]],i]
            else:
                dic[target-nums[i]] = i

 

 

 

 

 

參考文章

 

https://discuss.leetcode.com/topic/23004/here-is-a-python-solution-in-o-n-time

 

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