Two Sum II - Input Array Is Sorted

Intuition

The given Python code implements a two-pointer approach to find two numbers in a sorted array that add up to a specific target.The idea behind this approach is to maintain two pointers, left and right, initially pointing to the beginning and end of the array, respectively. Since the array is sorted in non-decreasing order, moving the pointers inward allows you to explore possible pairs efficiently.Also this problem can be solved by using hash map.

Approach

If the sum of the numbers at the left and right pointers is equal to the target, you have found the pair.
If the sum is greater than the target, move the right pointer to the left to decrease the sum.
If the sum is less than the target, move the left pointer to the right to increase the sum.
Repeat steps 1-3 until you find the pair.

Complexity

  • Time complexity:

The time complexity of this solution is O(n), where n is the length of the input array. In the worst case, you might need to traverse the entire array once to find the pair

  • Space complexity:

The space complexity is O(1), constant extra space. This is because the solution only uses a fixed number of pointers (left and right) and does not rely on additional data structures that scale with the size of the input

Code

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        left,right=0,len(numbers)-1
        while(numbers[left]+numbers[right]!=target):
            if numbers[left]+numbers[right]>target:
                right-=1
            elif numbers[left]+numbers[right]<target:
                left+=1
        
        return [left+1,right+1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值