您的位置:首页 > 编程语言 > Python开发

leetcode【1+167 Two Sum 系列】【python】

2016-09-01 19:31 453 查看

1 Two Sum

找到给定序列中两个数字的和是指定target,返回的是个list,包含两个数的index,从0开始。

第一反应肯定是遍历,毕竟是数组题,遍历需要两遍,才能找到和,那么肯定是要优化的了。

因为是查找,所以可以想到hash,查找只需要O(1)复杂度。那么维持一个dict,其中key是数值,value是数值对应的下标。最初的想法是从数组中每取到一个数字nums[i],判断nums[i]在不在dict中,后来想到它在不在没有太大的意义,它在也要进一步判断target-nums[i]是否存在,才能找到两个数字,它不在那么当然就是把nums[i]存进dict。所以呢,不如直接判断target-nums[i]是不是在,如果在,那么它对应的value肯定是返回数组res[0],nums[i]所在的第i位就是res[1]了,如果不在,还是一样把nums[i]放入。

代码如下:

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = dict()
result = [-1, -1]
for i in range(len(nums)):
if target-nums[i] in temp.keys():
result[1] = i
result[0] = temp.get(target - nums[i])
break
else:
temp[nums[i]] = i
return result


167 Two Sum II –Input array is sorted

跟上一题想多,改变有两处,一个是给定的数组是排好序的,另一个是返回的下标是从1开始的。当然后者对做题没有什么影响。我们仍然可以使用hash的方法来实现这个题。我也确实是这么做的。。。那么当第二遍做这道题的时候,我想到排序对这道题的改变,忽然就想到了two points,也就是夹逼的思想,哈哈哈。从头和从尾同时向内逼近。

class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 0
right = len(numbers) -1
while(left < right):
if(numbers[left] + numbers[right] == target):
return [left+1,right+1]
elif(numbers[left] + numbers[right] < target):
left += 1
else:
right -= 1


就是这样啦 这道题我们了解了夹逼、hash表。其实c++\jave\python这些都自带hash表功能的内置数据结果的,只有c木有啦,python里是dict(),key-value对应的这种形式。它自带很多方法,可以很灵活的使用嗒
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: