前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q167 Two Sum II - Input array is sorted

Q167 Two Sum II - Input array is sorted

作者头像
echobingo
发布2018-04-25 16:53:18
4140
发布2018-04-25 16:53:18
举报

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 and you may not use the same element twice.

代码语言:javascript
复制
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路:

参考题目: Q1 Two Sum

这道题与 Q1 Two Sum 不同的是给定的列表是排好序的。如果按照 Q1 Two Sum 的思路,时间复杂度和空间复杂度均为 O(n)。

既然是排序好的列表,那么就应该利用这样一个优势。

方法一:时间复杂度为 O(nlgn),空间复杂度为 O(1) 。具体做法就是依次遍历列表中的元素,得到目标值与元素的差值,然后在剩余的元素中采用二分查找。

方法二:时间复杂度为 O(n),空间复杂度为 O(1) 。利用两个指针,一个指向列表头,一个指向列表尾。将头尾两元素值相加与目标值相比,如果比目标值小,则头指针向前移动;否则,尾指针向后移动。不断缩小范围,直到找到相加值与目标值相等的两个元素,否则返回None。

程序实现最终采用了方法二。

注意点:

返回的索引不是从0开始的,而是从1开始的。

Python实现:
代码语言:javascript
复制
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        lens = len(numbers)
        if lens == 0:
            return None
        l, h = 0, lens - 1   # 头尾两个指针
        while l < h:     
            tar = numbers[l] + numbers[h]
            if tar == target:
                return [l+1, h+1]
            elif tar < target:
                l += 1
            else:
                h -= 1  
        return None

a = [2,3,5,7]
b = 10
c = Solution()
print(c.twoSum(a,b))   # [2,4]
总结:

方法二为两指针法,是一种常用的方法。它适用于排好序的列表

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • 注意点:
  • Python实现:
  • 总结:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档