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对应的这种形式。它自带很多方法,可以很灵活的使用嗒
相关文章推荐
- 【leetcode系列】Two Sum
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode:python]1.Two Sum
- leetcode python - Two Sum
- [leetcode刷题系列]Two Sum
- LeetCode 167 Two Sum 2-Input array is sorted
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- 【LeetCode】Two Sum 解题报告(java & python)
- [leetcode]-[Two Sum]-python实现
- 【python】【leetcode】【算法题目167—Two Sum II - Input array is sorted】
- 【python】【leetcode】【算法题目1—Two Sum】
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- leetcode 【 Two Sum 】python 实现
- LeetCode-two sum:python解答数组问题
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- python写算法题:leetcode: 1. Two Sum