1.Two Sum——Python实现

Description:
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].

渣翻:
        给出一列整数,请返回这列整数其中两个数的序列,要求这两个数的和等于给定的target值。
        假设每个输入只有一组解,并且不能够两次使用同一个位置上的数。

  • 最好想的方法:用两次for循环,时间复杂度为O(n^2)

  • 改进方法:使用哈希表。代码如下:

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

时间复杂度为O(n)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,041评论 0 23
  • 读书是一种享受,读好书则是一种机缘。恰如《万物皆有欢喜处》,于芸芸众书中选择了它,又从两百多本搁置待读的群书中抽出...
    坚持写字的猫阅读 473评论 0 1
  • 中国茶,源流长, 发神农,起汉唐。 先入药,后成汤,闻四海,传八方。 茶经书,陆羽撰,人工培,吴理真。 产茶区,布...
    Y啵啵哒阅读 501评论 0 0