lintcode刷题(python)——(4)

这篇博客介绍了如何解决已排序整数数组中找到两个数,使其和等于特定目标值的问题。文章着重讨论了如何在已排序的输入数组中找到解决方案,强调每个输入都有且仅有一个解。
友情提示:点击上面的“+”展开目录以便查看具体的题目生气
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]


### 使用Python进行计算机科学的最佳资源和平台 对于希望提升编程技能并准备技术面试的人来说,在线平台上练习算法问是必不可少的一环。LeetCode是一个非常受欢迎的选择,它提供了大量的目供用户挑战,并支持多种编程语言,其中包括Python[^2]。 另一个优秀的在线判网站是Codeforces, 这里定期举办竞赛活动以及拥有丰富的历史比赛目可以用来训练自己的解能力。值得注意的是,该站点同样允许参赛者采用Python编写解决方案[^3]。 除了上述两个主要平台外,HackerRank也值得一提。这个网站不仅提供了一系列针对不同主(如数据结构、算法等)的专项练习模块,而且特别强调实际应用场景下的编码技巧培养;同时,这里也有活跃的技术社区可供交流学习心得[^1]。 最后不得不提的就是国内知名的OJ系统——牛客网(NiuKe),其特色在于汇聚了大量的中文描述试,非常适合母语为汉语的学习者使用。此外,牛客网上还有许多关于各大公司笔试真分享的文章,能够帮助求职者更好地了解目标企业的要求。 ```python # 示例:在 LeetCode 上解决简单级别的 Python 编程问 class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ num_to_index = {} for i, num in enumerate(nums): complement = target - num if complement in num_to_index: return [num_to_index[complement], i] num_to_index[num] = i ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值