美文网首页
【python学习记录1】Two Sum

【python学习记录1】Two Sum

作者: hitsunbo | 来源:发表于2016-08-28 20:45 被阅读1451次

问题描述

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.

Example:

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

详细问题

代码实现

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        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

经验总结

  • python中的字典dictionary在查找key时使用的是hashmap的方式,查找速度较快
  • 定义新的缓冲区,可以得到“空间换时间”的效果,降低时间复杂度

相关文章

网友评论

      本文标题:【python学习记录1】Two Sum

      本文链接:https://www.haomeiwen.com/subject/pyqxettx.html