leetcode--two_sum问题

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中存在重复值时,该方法不适用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值