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 = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
这道题是进入leetcode的第一道题目,大致的思路最开始就是暴力解法,将数组中的每两个数相加,然后和target相比,计算了下复杂度,大概在O(n2)。换个思路,用target减去当前的数,在从数组中查询是否存在这个数。但是没有想到hash的办法,导致其实复杂度还是在O(n2)。但也通过了测试,看了网上有很多种办法,可以逐一学习一下。
主要的方法有两种:
1. 先排序然后用双指针向中间夹逼,复杂度O(nlogn)
2. 用Map记录出现过的数,查找有没有跟当前的数构成target,复杂度为O(nlogn)。相对于自己直接的比较,还是用了hash比较快
方法一,跑下来的速度在40ms
class Solution(object):
def twoSum(self, nums, target):
nums_sorted = sorted(nums)
left = 0
right = len(nums) - 1
while True:
if nums_sorted[left] + nums_sorted[right] == target:
post1 = nums.index(nums_sorted[left])
post2 = nums.index(nums_sorted[right])
if post2 == post1:
post2 = nums[post1+1:].index(nums_sorted[right]) + post1 + 1
return min(post1+1, post2+1), max(post1+1, post2+1)
elif nums_sorted[left] + nums_sorted[right] < target:
left += 1
elif nums_sorted[left] + nums_sorted[right] > target:
right -= 1
方法二,跑下来的速度在48ms反而慢了些
class Solution(object):
def twoSum(self, nums, target):
map = {}
for i, value in enumerate(nums):
if target-value in map:
return map[target-value]+1, i+1
else:
map[value] = i

796

被折叠的 条评论
为什么被折叠?



