您的位置:首页 > 其它

leetcode--two_sum问题

2016-09-12 23:01 363 查看

leetcode–two_sum问题

2016-09-12

问题描述: 给定一个排好序的整数数组,使得两数相加等于一个特定的值。

要求: 返回两个数在数组中的索引,第一个数的索引必须小于第二个;数组的起始下标不是从0开始的。

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

解题思路

假设数组为numbers[],设置收尾指针head和tail,

当numbers[head] + numbers[tail] < target时,head加1;

当numbers[head] + numbers[tail] > target时,tail减1;

当numbers[head] + numbers[tail] = target 或者 head > tail时,算法终止。

算法最终的时间复杂度为O(n)。

python程序

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

if __name__ == '__main__':
temp = input('please enter a list:')
nums = [int(i) for i in temp.split(' ')]
target = int(input('please enter an int: '))
Solution().twoSum(nums, target)


源程序下载

原题变形

如果给定的整数数组没有排好序,如何解决两数相加等于一个特定值问题。

解题思路1

先将表排序排序,再按照上述方法做,时间复杂度为O(n*logn)。

解题思路2

使用HashMap,因为每次HashMap(python中为dict)找key都只要O(1)的时间复杂度,可以将原数组numbers中的值作为key,索引作为value,遍历一遍放到HashMap中。再通过遍历numbers数组中的值x,查找target-x是否为HashMap的key,此过程时间复杂度为O(n)。综上,使用HashMap的时间复杂度为O(n),空间复杂度也为O(n)。

Tips: 当numbers中存在重复值时,该方法不适用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode