【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的更多相关文章

  1. [LeetCode 题解]:Path Sum

    前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述 Given a bi ...

  2. LeetCode 18: 4 Sum 寻找4数和

    链接 4Sum 难度 Medium 描述 Given an array nums of n integers and an integer target, are there elements a , ...

  3. LeetCode 363:Max Sum of Rectangle No Larger Than K

    题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...

  4. 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 ...

  5. 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 ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. leetcode笔记:Range Sum Query - Mutable

    一. 题目描写叙述 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), ...

  10. leetcode series:Two Sum

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

随机推荐

  1. BZOJ 1202 [HNOI2005]狡猾的商人(并查集)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1202 [题目大意] 给出一些区间和的数值,问是否存在矛盾 [题解] 用并查集维护前缀和 ...

  2. ubuntu BCM43142 lenovo网卡驱动安装(Broadcom)

    ubuntu13.10 lenovo网卡驱动安装(Broadcom)   ubuntu当月刚出了13.10版本,在升级了操作系统版本后无法搜索无线热点,联想官网提供的驱动下载都是为windows准备的 ...

  3. 调整Chrome中文字体为雅黑

    几天试了一下Chrom发布的Chrome 37,感觉所谓的Direct2D渲染还是有些效果的,但这只体现在英文上,中文的宋体还是非常的不舒服,便试着将其替换成了雅黑,这里介绍一下相关方法. Chrom ...

  4. mysql-operator 尝试与研究

    安装指南 先下载到本地 git clone https://github.com/kubernetes/charts.git 安装helm 参考: http://www.cnblogs.com/eri ...

  5. 较详细的介绍JNI

    JNI其实是Java Native Interface的简称,也就是java本地接口.它提供了若干的API实现了和Java和其他语言的通信(主要是C&C++).也许不少人觉得Java已经足够强 ...

  6. DevExpress 自动匹配宽度,及其他使用笔记

    摘自: http://blog.sina.com.cn/s/blog_53b58e7c0101avl4.html GridControl列自动匹配宽度 -- : 327人阅读 评论() 收藏 举报 / ...

  7. java HashMap,LinkedHashMap,TreeMap应用

    共同点: HashMap,LinkedHashMap,TreeMap都属于Map:Map 主要用于存储键(key)值(value)对,根据键得到值,因此键不允许键重复,但允许值重复. 不同点: 1.H ...

  8. Java Web----EL(表达式语言)详解

     Java Web中的EL(表达式语言)详解 表达式语言(Expression Language)简称EL,它是JSP2.0中引入的一个新内容.通过EL可以简化在JSP开发中对对象的引用,从而规范页面 ...

  9. TCP的状态(SYN,FIN等)

    TCP的标志位有SYN,FIN,RST,ACK,PSH,URG SYN:建立连接. FIN:关闭连接. RST:连接重置. ACK:响应. PSH:有数据传输. URG:urgent紧急. ACK可以 ...

  10. Converter -> public static int ToInt32(double value) 你用对了么?

    Convert.ToInt32()  是我们经常使用的方法,但如果我们写如下的代码,能确定它的输出值么? var x = 7.5; Console.WriteLine(7.5 + ": &q ...