# -*- coding: utf8 -*-
'''
https://oj.leetcode.com/problems/two-sum/ 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 ===Comments by Dabay===
这道题描述中没有讲明对时间复杂度的要求。
用一个while循环嵌套另外一个while循环,时间复杂度为O(NlgN)。
这里可以用空间来换时间,用O(N)空间来存储每个数的位置,这样就可以用O(N)的时间来找到答案。
因为hash表的命中时间是O(1)。 但是,先遍历一次num,存储所有的数字到hash表中;再遍历一次来查找结果,还是会超时。 考虑其实不需要存储所有的数字到hash表中,因为只要在已经存在的hash表中有我们需要的答案就可以啦。
所以一次遍历的时候,查找是否有我们需要的答案,如果没有添加这个数字到hash表中。 此题答案要求的index是我们数组index+1的,所以返回的时候各加1。
''' class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
dict = {}
for i in xrange(len(num)):
expected = target - num[i]
if expected in dict.keys():
return (dict[expected]+1, i+1)
dict[num[i]] = i def main():
s = Solution()
nums = [-3,4,3,90]
print s.twoSum(nums, 0) if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)

[LeetCode][Python]Tow Sum的更多相关文章

  1. 【leetcode❤python】Sum Of Two Number

    #-*- coding: UTF-8 -*- #既然不能使用加法和减法,那么就用位操作.下面以计算5+4的例子说明如何用位操作实现加法:#1. 用二进制表示两个加数,a=5=0101,b=4=0100 ...

  2. 【leetcode❤python】 Sum of Left Leaves

    #-*- coding: UTF-8 -*- # Definition for a binary tree node.# class TreeNode(object):#     def __init ...

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

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

  4. [LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  5. Leetcode Python Solution(continue update)

    leetcode python solution 1. two sum (easy) Given an array of integers, return indices of the two num ...

  6. [LeetCode] 1. Two Sum 两数和

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  7. [LeetCode] 40. Combination Sum II 组合之和 II

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  8. [LeetCode] 112. Path Sum 路径和

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  9. [LeetCode] 113. Path Sum II 路径和 II

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

随机推荐

  1. JS判断是否在微信浏览器打开

    if (browser.versions.mobile) {//判断是否是移动设备打开.browser代码在下面 var ua = navigator.userAgent.toLowerCase(); ...

  2. 树莓派设置成无线路由(AP)

    1.安装需要的包 sudo apt-get install hostpad uhdcpd 2.配置/etc/network/interfaces文件 配置wlan0为静态地址 格式如下: iface ...

  3. 去掉ILDasm的SuppressIldasmAttribute限制

    原文:去掉ILDasm的SuppressIldasmAttribute限制 今天本打算汉化一个.Net程序的,当用ILDasm打开的时候,出现了"受保护模块—无法进行反汇编"的错误 ...

  4. Nginx 介绍和安装

    Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器. Nginx 是由 Igor Sysoev ...

  5. 关于chrome浏览器更新后快捷工具失效的解决方法

    更新chrome浏览器到29.0时发现快捷工具的双击关闭标签页失效了,解决办法: 1.打开chrome的文件夹.C:\Program Files (x86)\Google\Chrome\Applica ...

  6. 04737_C++程序设计_第1章_认识C++的对象

    例1.1 演示使用结构对象的示例程序. //功能:将结构对象的两个域值相加,乘以2再加50 #include <iostream>//包含头文件 using namespace std;/ ...

  7. uva 10004 Bicoloring(dfs二分染色,和hdu 4751代码差不多)

    Description In the ``Four Color Map Theorem" was proven with the assistance of a computer. This ...

  8. POJ 2029 DP || 暴力

    在大矩形中找一个小矩形 使小矩形包括的*最多 暴力或者DP  水题 暴力: #include "stdio.h" #include "string.h" int ...

  9. SQL函数介绍

    http://www.cnblogs.com/moss_tan_jun/archive/2010/08/23/1806861.html 一旦成功地从表中检索出数据,就需要进一步操纵这些数据,以获得有用 ...

  10. There is no result type defined for type 'json' mapped with name 'success'. Did you mean 'json'?

    错误信息: 严重: Exception starting filter struts2 Unable to load configuration. - action - file:/C:/Users/ ...