LeetCode-1:Two Sum
【Problem:1-Two Sum】
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 = [, , , ], target = , Because nums[] + nums[] = + = ,
return [, ].
【Solution】
1)-----------Submission Status :Time Limit Exceeded
Time complexity:O(n^2)2).
【Python】
import time
class Solution(object):
def twoSum(self,nums,target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j start = time.clock()
test=Solution()
nums=[1,2,3,4,5,55,26,25,36,211,200,300,258,459]
target=8
print("The indices are :",test.twoSum(nums,target)) end = time.clock()
c=end-start
print("Runtime is :",c)

可是 Java 的这个,Time complexity 也是O(n^2)2 ,却可以 AC??
【Java】
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
2)两个方法做个对比:(Python 语言)
#----
class Solution(object):
# Method 1 : O(n_2)
def twoSum1(self,nums,target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j # Method 2 : O(n)
def twoSum2(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i test=Solution()
nums=[1,2,3,4,5,55,26,25,36]
target=8 start1 = time.clock()
print("The indices of method1 are :",test.twoSum2(nums,target))
end1 = time.clock()
t1=end1-start1
print("Runtime1 is :",t1) start2 = time.clock()
print("The indices of method2 are :",test.twoSum2(nums,target))
end2 = time.clock()
t2=end2-start2
print("Runtime2 is :",t2)
结果是:

3)外加一个方法3 ,会比法2好些?(亦可AC)
#----
class Solution(object):
# Method 1 : O(n_2)
def twoSum1(self,nums,target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j # Method 2 : O(n)
def twoSum2(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i def twoSum3(self, num, target):
tmp_num = {}
for i in range(len(num)):
if target - num[i] in tmp_num:
# here do not need to deal with the condition i = target-i
return (tmp_num[target-num[i]], i)
else:
tmp_num[num[i]] = i
return (-1, -1) test=Solution()
nums=[1,2,3,4,5,55,26,25,36]
target=8 start1 = time.clock()
print("The indices of method1 are :",test.twoSum2(nums,target))
end1 = time.clock()
t1=end1-start1
print("Runtime1 is :",t1) start2 = time.clock()
print("The indices of method2 are :",test.twoSum2(nums,target))
end2 = time.clock()
t2=end2-start2
print("Runtime2 is :",t2) start3 = time.clock()
print("The indices of method3 are :",test.twoSum3(nums,target))
end3 = time.clock()
t3=end3-start3
print("Runtime3 is :",t3)
结果是:

LeetCode-1:Two Sum的更多相关文章
- [LeetCode 题解]:Path Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a bi ...
- LeetCode 18: 4 Sum 寻找4数和
链接 4Sum 难度 Medium 描述 Given an array nums of n integers and an integer target, are there elements a , ...
- LeetCode 363:Max Sum of Rectangle No Larger Than K
题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...
- LeetCode OJ:Range Sum Query 2D - Immutable(区域和2D版本)
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...
- LeetCode OJ:Range Sum Query - Immutable(区域和)
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -&g ...
- LeetCode OJ:Three Sum(三数之和)
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- LeetCode OJ: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 ...
- LeetCode OJ:Path Sum(路径之和)
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- leetcode笔记:Range Sum Query - Mutable
一. 题目描写叙述 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), ...
- leetcode series:Two Sum
题目: Given an array of integers, find two numbers such that they add up to a specific target number. ...
随机推荐
- BZOJ 4939 [Ynoi2016]掉进兔子洞(莫队+bitset)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4939 [题目大意] 给出一个数列,每个询问给出三个区间,问除去三个区间共有的数字外, ...
- BZOJ 1116 [POI2008]CLO(并查集)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1116 [题目大意] Byteotia城市有n个towns,m条双向roads.每条ro ...
- [转]115个Java面试题和答案——终极列表(下)
第一篇讨论了面向对象编程和它的特点,关于Java和它的功能的常见问题,Java的集合类,垃圾收集器,本章主要讨论异常处理,Java小应用程序,Swing,JDBC,远程方法调用(RMI),Servle ...
- SSL协议的握手过程(摘录)
SSL协议的握手过程 为了便于更好的认识和理解 SSL 协议,这里着重介绍 SSL 协议的握手协议.SSL 协议既用到了公钥加密技术(非对称加密)又用到了对称加密技术,SSL对传输内容的加密是采用的对 ...
- WPF中的动画——(四)缓动函数
缓动函数可以通过一系列公式模拟一些物理效果,如实地弹跳或其行为如同在弹簧上一样.它们一般应用在From/To/By动画上,可以使得其动画更加平滑. var widthAnimation = new D ...
- 异常:System.BadImageFormatException,未能加载正确的程序集XXX或其某一依赖项
常:System.BadImageFormatException,未能加载正确的程序集XXX或其某一依赖项 看到这个异常,我估计谁都会头大一阵子,不过还好,由于前面知道要设置为x86,加上以前观察过I ...
- 【shiro】使用shiro,点击页面请求总是302状态码
解决方法: 配置shiro中,将要求放过的地址后面加上后缀,这里是.htmls 因为web.xml中配置所有的页面都是放过的
- ejs循环实例
... //index page var items=[{title:"文章1"},{title:"文章2"}]; app.get('/',function(r ...
- java8 遍历数组的几种方式
java8 遍历数组的几种方式 2017年04月05日 09:15:46 阅读数:4640 风格色 2017-02-11 18:41 有如下一个String数组 String[] array = {& ...
- InfluxDB写流程
Influxdb version1.8 HTTP: 0x00000000016d0ce3 in github.com/influxdata/influxdb/coordinator.(*PointsW ...