【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. 2017 icpc 南宁网络赛

    2000年台湾大专题...英语阅读输入输出专场..我只能说很强势.. M. Frequent Subsets Problem The frequent subset problem is define ...

  2. 【树形dp】Distance in Tree

    [CF161.D] Distance in Tree time limit per test 3 seconds memory limit per test 512 megabytes A tree  ...

  3. 【POJ】1088滑雪

    滑雪 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 97335   Accepted: 36911 Description ...

  4. HDU 6053 TrickGCD(分块)

    [题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6053 [题目大意] 给出一个数列每个位置可以取到的最大值, 问这个可以构造多少个数列,使得他们的最 ...

  5. BZOJ 1116 [POI2008]CLO(并查集)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1116 [题目大意] Byteotia城市有n个towns,m条双向roads.每条ro ...

  6. bzoj 1433: [ZJOI2009]假期的宿舍

    1433: [ZJOI2009]假期的宿舍 Description Input Output Sample Input 1 3 1 1 0 0 1 0 0 1 1 1 0 0 1 0 0 Sample ...

  7. 修改activityMQ的登录账与密码

    登录下管理员页面,ip根据实际的来 URL : http://127.0.0.1:8161/admin/ 默认账户密码都是admin 账户密码修改在conf文件夹下的jetty-realm.prope ...

  8. 【java】java中替换中括号[ ]操作

    String aa ="[1,2,3]"; aa = aa.replaceAll("[\\[\\]]",""); 结果为 1,2,3

  9. google的开源项目总结

    转自http://www.feng5166.com/blog/424.html google的开源项目值得我们一用的,这些项目很有意义,甚至可以直接用在我们自己的工作上!学习编程的的一个比较好的方式就 ...

  10. 一份不太简短的LaTeX教程 lshort – A short in­tro­duc­tion to LATEX 2elshort – A short in­tro­duc­tion to LATEX 2e

    Lshort started as a trans­la­tion and ra­tio­nal­i­sa­tion of a ground-break­ing Ger­man-lan­guage i ...