博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
TwoSum
阅读量:5155 次
发布时间:2019-06-13

本文共 1269 字,大约阅读时间需要 4 分钟。

 

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

 

转载于:https://www.cnblogs.com/szzshi/p/6945167.html

你可能感兴趣的文章
Exceptions, Catch, and Throw(Chapter 10 of Programming Ruby)
查看>>
Abstract Factory(Chapter 5 of Pro Objective-C Design Patterns for iOS)
查看>>
SVN错误:Attempted to lock an already-locked dir及不能提交.so文件
查看>>
Oracle sessions,processes 和 transactions 参数 关系 说明
查看>>
ES6中的新特性
查看>>
前端QRCode.js生成二维码(解决长字符串模块和报错问题)
查看>>
CGI、FastCGI和php-fpm的概念和区别
查看>>
spring test---restful与文件上传
查看>>
poj1161Post Office【经典dp】
查看>>
Kolya and Tandem Repeat
查看>>
轻量级过程改进项目启动
查看>>
让我们来谈谈合并排序算法
查看>>
数据挖掘十大经典算法(9) 朴素贝叶斯分类器 Naive Bayes
查看>>
C# 通过Exchange server 发送邮件
查看>>
ORACLE EXP命令
查看>>
多态应用-打印商品价格案例
查看>>
ng-option小解
查看>>
Appium appium android 6.0+ 微信 @driver.available_contexts 返回 webview_undefined 问题
查看>>
(转)运维角度浅谈MySQL数据库优化
查看>>
C#面向对象基础(四) 静态成员与实例成员
查看>>