Leetcode: 1. Two Sum [python]

来源:互联网 发布:淘宝卖家可以不发货吗 编辑:程序博客网 时间:2024/05/17 22:44
  1. Two Sum
    地址:https://leetcode.com/problems/two-sum/#/description
    Python
class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        return_list = []        #dict = {}        for i in range(0,len(nums)):            #list = []            for j in range(i+1,len(nums)):                #print i,j                temp = nums[i]+nums[j]                if temp == target:                   return [i,j]         #print return_list        #return return_list

用了双循环,时间复杂度肯定是O(n^2)还是比较复杂的,看看别人的参考a Python solution in O(n) time:
https://leetcode.com/problems/two-sum/#/solutions

class Solution(object):    def twoSum(self, nums, target):        if len(nums) <= 1:            return False        buff_dict = {}        for i in range(len(nums)):            if nums[i] in buff_dict:                return [buff_dict[nums[i]], i]            else:                buff_dict[target - nums[i]] = i

每遍历一个数,把target减去该数的值存入buff_dict中,如果在接下来的数中有,直接返回两数index

0 0
原创粉丝点击