zoukankan      html  css  js  c++  java
  • TwoSum

    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.

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

    ==================================================

    The idea is to search target -num in the given nums.  

    Since the task assumes that each input would have exactly one solution, means that there is one and only one solution to get the specific target. 

    _ver2 is better, it searches the target-num in the saved lookup dictionary when saving the num in the lookup dictionary one by one. This method could save the space and also prevent the index overwriting when there are two same values in the nums. 

    """ Implement the search by list.count and index"""

    def twoSum_ver1(self,nums,target):
      for cnt,num in enumerate(nums):
        if nums.count(target-num) >0 and nums.index(target-num)!=cnt:
          return [cnt,nums.index(target-num)]

    def twoSum_ver3(self,nums,target):
      lookup = {}
      for cnt, num in enumerate(nums):
        if target - num in lookup:
          return [lookup[target-num],cnt]
      lookup[num] = cnt

  • 相关阅读:
    迭代器实现斐波那契数列
    type 创建类,赋予类静态方法等
    使用types库修改函数
    使用property取代getter和setter方法
    pdb 进行调试
    nonlocal 访问变量
    timeit_list操作测试
    metaclass 拦截类的创建,并返回
    isinstance方法判断可迭代和迭代器
    苹果cms10 官方QQ微信防红防封代码
  • 原文地址:https://www.cnblogs.com/szzshi/p/6945167.html
Copyright © 2011-2022 走看看