it渣渣记录自己的刷题之路
Question:
1. Two Sum. (Easy)
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 sameelement twice.
拿到题目,首先想到的就是两层嵌套的for循环,一开始准备写python3,但发现题目给出的是class的形式,已经一学期没有用过python 的我有些虚,所以决定先用Js来写一个简单版的。
Js版本答案如下:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for(let i = 0; i< nums.length-1; i++){
for (let j = i+1; j< nums.length; j++){
if (nums[i]+nums[j] == target){
return [i,j];
}
}
}
};
运行成功,但结果并不是特别的优秀,反馈如下:
Runtime:104 ms, faster than 46.95% of JavaScript online submissions for Two Sum.
Memory Usage:34.6 MB, less than 72.32% of JavaScript online submissions for Two Sum.
决定采用python方法做一遍,试一下有什么不同,代码如下:
python 2:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
结果如下:
Runtime:4860 ms, faster than 14.61% of Python online submissions for Two Sum.
Memory Usage:12.4 MB, less than 95.21% of Python online submissions for Two Sum.
python 3:
class Solution:
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]
结果:
Runtime:5292 ms, faster than 19.35% of Python3 online submissions for Two Sum.
Memory Usage:14.8 MB, less than 15.58% of Python3 online submissions for Two Sum.
在内存上有了很大的进步,但发现运行速度是Js的四十倍。
下面决定优化python算法,采用hash,减少一层循环,试图来提高速度:
首先采用了一个错误的方法,代码如下:
class Solution(object):
def twoSum(self, nums, target):
for i in nums:
if target-i in nums:
if nums.index(i) == nums.index(target-i):
return [nums.index(i),nums.index(target-i)]
这种方法没有考虑到3+3 = 6的情况,即target 可以由两倍的自己组成,则也会返回相应的错误结果。
如是进行了更正:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = dict();
for i,x in enumerate(nums):
if target-x in dic:
return [i, dic[target-x]]
else:
dic[x]=i
这种存方法导致,只能往前找,即不能自己与自己配对
运行结果如下:
Runtime:36 ms, faster than 75.47% of Python online submissions for Two Sum.
Memory Usage:13.2 MB, less than 31.85% of Python online submissions for Two Sum.
在速度上有了提升
如果我们只是把else删除,发现会有在内存和速度上都会有提升:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = dict();
for i,x in enumerate(nums):
if target-x in dic:
return [i, dic[target-x]]
dic[x]=I
结果如下:
Runtime:28 ms, faster than 97.57% of Python online submissions for Two Sum.
Memory Usage:13 MB, less than 60.27% of Python online submissions for Two Sum.
~~~ end ~~~
等有时间会再用c来做一下