【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. leetcode 564. Find the Closest Palindrome

    leetcode564题目地址 Given an integer n, find the closest integer (not including itself), which is a pali ...

  2. Smart config风险分析与对策

    Smart config风险分析与对策 1.简介:          Smart config是一种将未联网设备快速连接wifi的技术,大概原理如下图所示: 2.业务需求:          要求实现 ...

  3. <摘录>算法策略的总结

    策略是面向问题的,算法是面向实现的. 一.不同算法策略特点小结 1.贪心策略 贪心策略一方面是求解过程比较简单的算法,另一方面它又是对能适用问题的条件要求最严格(即适用范围很小)的算法. 贪心策略解决 ...

  4. Inno Setup入门(十八)——Inno Setup类参考(4)

    http://379910987.blog.163.com/blog/static/3352379720112122533866/ 编辑框 编辑框也叫文本框,是典型的窗口可视化组件,既可以用来输入文本 ...

  5. Fork & vfork & clone (转载)

    转自:http://blog.csdn.net/zqy2000zqy/archive/2006/09/04/1176924.aspx 进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合, ...

  6. CDHtmlDialog 基本使用

    跳转 Navigate("res://tt.exe/#138"); 138是html的资源号 输入框的Get,set HRESULT CTTDlg::OnButtonCancel( ...

  7. 通过JSONP实现完美跨域

    通过JSONP实现完美跨域 三水清 2010-06-11 20:17:47 以前我经常在博客说JSONP,例如我的WordPress天气插件就是通过JSONP来调用的天气数据,今天就说说通过JSONP ...

  8. iOS:quartz2D绘图(绘制渐变图形)

    quartzD可以用来绘制渐变图形,即图形向外或向内发散,会变得越来越模糊. 渐变分为线性渐变和径向渐变,所谓线性渐变,就是图形以线的方式发散,发散后一般呈现出矩形的样子:而径向渐变,就是以半径的大小 ...

  9. ISP图像调试工程师——对比度增强(熟悉图像预处理和后处理技术)

    经典对比度增强算法: http://blog.csdn.net/ebowtang/article/details/38236441

  10. SpringMVC防止XSS注入

    xss(Cross Site Scripting)注入就是,跨站脚本攻击,和sql注入类似的,在请求中添加恶意脚本,实现控制用户. XssHttpServletRequestWrappe.java 重 ...