nathanwailes

LeetCode 167 - Two Sum II - 2023.10.08 solution

Oct 7th, 2023
1,236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. class Solution:
  2.     def twoSum(self, numbers: List[int], target: int) -> List[int]:
  3.         """
  4.        [2,7,11,15], target = 18
  5.        Step 1: 17, we need more, so step in from the left
  6.        Step 2: 22, we need less, so step in from the right
  7.  
  8.        Proposed solution: We start with the two pointers at the ends and
  9.        step inwards based on whether the current sum is greater or less
  10.        than the target sum.
  11.        """
  12.         l = 0
  13.         r = len(numbers) - 1
  14.  
  15.         while l < r: # TODO: Double-check this condition.
  16.             current_sum = numbers[l] + numbers[r]
  17.             if current_sum == target:
  18.                 return [l+1, r+1]
  19.             elif current_sum < target:
  20.                 l += 1
  21.             else:
  22.                 r -= 1
  23.  
Advertisement
Add Comment
Please, Sign In to add comment