lintcode刷题(python)——(4)

Lintcode Python刷题解析:两数之和(排序数组)
这篇博客介绍了如何解决已排序整数数组中找到两个数,使其和等于特定目标值的问题。文章着重讨论了如何在已排序的输入数组中找到解决方案,强调每个输入都有且仅有一个解。
友情提示:点击上面的“+”展开目录以便查看具体的题目生气
Two Sum - Input array is sorted 

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

 注意事项

You may assume that each input would have exactly one solution.

样例

Given nums = [2, 7, 11, 15], target = 9
return [1, 2]

这道题特别简单,唯一要注意的一点就是有相同数字时的处理,如[1,1,3,4] target=2,方法见下面代码。

class Solution:
    """
    @param nums {int[]} n array of Integer
    @param target {int} = nums[index1] + nums[index2]
    @return {int[]} [index1 + 1, index2 + 1] (index1 < index2)
    """
    def twoSum(self, nums, target):
        # Write your code here
        for i in range(len(nums)):
            if target-nums[i] in nums:
                if (target-nums[i])!=nums[i]:
                    return [i+1,nums.index(target-nums[i])+1]
                else:
                    if nums.count(nums[i])>1:
                        return [i+1,nums.index(target-nums[i])+2]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值