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. ...
随机推荐
- JZYZOJ1384 种花小游戏 状压dp
http://172.20.6.3/Problem_Show.asp?id=1384 最开始以为是dfs然后超时了,然后调了半天调成dp,还不如再写一遍... 代码 #include<iost ...
- [NOIp2017提高组]逛公园
题目大意: 给你一个有向图,若用dis(u,v)表示从u到v的最短路长度,求从1到n的长度不超过dis(1,n)+k的路径数. 思路: 首先分别预处理出以1,n为起点的单.源最短路. 对于合法的边重构 ...
- 输入sql语句,将结果写入到xml文件
import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DriverManager; import j ...
- git 推送内容到远程新分支
之前在做项目的时候,自己想将东西传到远程的一个新分支上.自己开始弄的时候稀里糊涂弄上去的也没搞清楚原理,不过自己后来又去试了一下,发现下面这个方法还可以. (1)在本地的一个目录下,git bash ...
- rman catalog配置简要笔记
服务端配置: SQL> create tablespace tbs_rman datafile 'H:\oradata\test\tbs_rman.dbf' size 20m autoexten ...
- DH密钥交换和ECDH原理(转)
DH密钥交换和ECDH原理 时间 2013-06-24 18:50:55 CSDN博客相似文章 (0) 原文 http://blog.csdn.net/sudochen/article/detail ...
- jQuery中的Ajax全局事件
Ajax全局事件 全局事件会在有ajax请求的情况下触发. 方法名称 说明 ajaxStart(callback) Ajax请求开始时执行的函数 ajaxStop(callback) Ajax请求结束 ...
- 课程学习:Linux系统管理
版本 内核版本 发行版本 常见Linux发行版本 ubuntu: 易用,可靠:技术支持付费,生态稍弱 debin: 精简,稳定,可靠; 更新较慢, 无技术支持,软件过时, 企业不太用 opensuse ...
- iOS开发--地图与定位
概览 现在很多社交.电商.团购应用都引入了地图和定位功能,似乎地图功能不再是地图应用 和导航应用所特有的.的确,有了地图和定位功能确实让我们的生活更加丰富多彩,极大的改变了我们的生活方式.例如你到了一 ...
- 云计算与OpenStack(虚拟机Nova篇)
<云计算与OpenStack(虚拟机Nova篇)> 基本信息 作者: 伯龙 程志鹏 张杰 出版社:电子工业出版社 ISBN:9787121201202 上架时间:2013-8-5 出版日期 ...