题目简述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

解题思想:

首先我很是不甘心的直接暴力了一次,果断TLE。然后想到先排序,然后两个指针前后搜,大了就后面的指针前移,小了就前面的指针后移。不过比较麻烦的是要找出原来的位置,导致代码多了几个丑陋的循环。

#coding=utf-8
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
t = []
for i in num:
t.append(i)
num.sort()
l = len(num)
index1 = 0
index2 = l-1
while index1 < index2:
if num[index1] + num[index2] == target:
break
elif num[index1] + num[index2] > target:
index2 -= 1
elif num[index1] + num[index2] < target:
index1 += 1
for i in range(l):
if num[index1] == t[i]:
index1 = i
break
for i in range(l):
if num[index2] == t[i] and i != index1:
index2 = i
break
if index1 >index2:
return index2+1,index1+1
return index1+1,index2+1

不过后来看到的标准解法里用了哈希表,We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index。于是就用dict写了下,不过可能是python的dict比较慢还是怎么,速度几乎一样,不过代码倒是短了不少。

class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
t = {}
l = len(num)
for i in range(l):
t[num[i]] = i
for i in range(l):
if t.has_key(target-num[i]):
if i != t[target-num[i]]:
return i+1 , t[target-num[i]]+1

【leetcode】Two Sum的更多相关文章

  1. 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)

    [LeetCode]129. Sum Root to Leaf Numbers 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/pr ...

  2. 【leetcode】907. Sum of Subarray Minimums

    题目如下: 解题思路:我的想法对于数组中任意一个元素,找出其左右两边最近的小于自己的元素.例如[1,3,2,4,5,1],元素2左边比自己小的元素是1,那么大于自己的区间就是[3],右边的区间就是[4 ...

  3. 【LeetCode】633. Sum of Square Numbers

    Difficulty: Easy  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/sum-of-square-n ...

  4. 【Leetcode】404. Sum of Left Leaves

    404. Sum of Left Leaves [题目]中文版  英文版 /** * Definition for a binary tree node. * struct TreeNode { * ...

  5. 【LeetCode】Two Sum II - Input array is sorted

    [Description] Given an array of integers that is already sorted in ascending order, find two numbers ...

  6. 【leetcode】Path Sum IV

    If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...

  7. 【LeetCode】Path Sum(路径总和)

    这道题是LeetCode里的第112道题.是我在学数据结构——二叉树的时候碰见的题.题目要求: 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和 ...

  8. 【LeetCode】Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)

    这道题是LeetCode里的第1005道题. 题目描述: 给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次. ...

  9. 【LeetCode】404. Sum of Left Leaves 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目大意 题目大意 解题方法 递归 迭代 日期 [LeetCode] 题目地址:h ...

  10. 【LeetCode】1022. Sum of Root To Leaf Binary Numbers 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetco ...

随机推荐

  1. 上传AppStore出现:Unexpected CFBundleExecutable Key 错误

    解决办法:就是把无用的CFBundle删除掉. 根据提示,找到对应第三方的SDK, 找到第三方的info.plist文件,删除里面的Executable file对应的一整行,包括值.

  2. [转]Java compiler level does not match解决方法

    查看链接:http://jingyan.baidu.com/article/95c9d20da3ec5fec4e756186.html

  3. nginx 反向代理

    nginx 反向代理 vim nginx.conf http { ..... upstream "tomcatweb" { server 172.30.13.199:8080; s ...

  4. BZOJ 1078: [SCOI2008]斜堆

    1078: [SCOI2008]斜堆 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 770  Solved: 422[Submit][Status][ ...

  5. iOS音乐播放器相关

    iOS音乐播放器框架主要有两大类:AvPlayer.AvaudioPlayer AvPlayer 能播放本地及网络歌曲 AvaudioPlayer 能播放本地歌曲.有相关代理方法(其实也可以播放网络歌 ...

  6. 测试dns

    测试dns nslookup test.cn 10.109.68.114 ipconfig /flushdns dig test.cn @10.109.68.114 sudo /etc/init.d/ ...

  7. 20145204&20145212信息安全系统实验一

    信息安全系统实验报告 博客链接

  8. Debian 8安装中文字体

    1.使用的镜像是debian-8.3.0-amd64-kde-CD-1.iso,下载链接可在Debian网站找到,系统安装完成后中文显示为方框 2.安装字体 apt-get install xfont ...

  9. 小白搭建一个网站(DouPHP)

    1)安装phpStudy_2014_setup.1413444920.exe 并启动数据库 2)将软件自带的WWW实例替换成我发的这个模板(DouPHP),网上也可以下载. 能找到更好模板的也可以不用 ...

  10. [Nhibernate]SchemaExport工具的使用(二)——创建表及其约束、存储过程、视图

    目录 写在前面 文档与系列文章 表及其约束 存储过程 视图 总结 写在前面 由于一直在山西出差,有几天没更新博客了.昨晚回到家,将博客园最近三天更新的文章搜集了一下,花费了半天的时间,看了看,有些文章 ...