|
| 1 | +# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ |
| 2 | + |
| 3 | +''' |
| 4 | +Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. |
| 5 | +Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. |
| 6 | +The tests are generated such that there is exactly one solution. You may not use the same element twice. |
| 7 | +Your solution must use only constant extra space. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: numbers = [2,7,11,15], target = 9 |
| 11 | +Output: [1,2] |
| 12 | +Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. |
| 13 | +
|
| 14 | +Example 2: |
| 15 | +Input: numbers = [2,3,4], target = 6 |
| 16 | +Output: [1,3] |
| 17 | +Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. |
| 18 | +
|
| 19 | +Example 3: |
| 20 | +Input: numbers = [-1,0], target = -1 |
| 21 | +Output: [1,2] |
| 22 | +Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. |
| 23 | + |
| 24 | +
|
| 25 | +Constraints: |
| 26 | +
|
| 27 | +2 <= numbers.length <= 3 * 104 |
| 28 | +-1000 <= numbers[i] <= 1000 |
| 29 | +numbers is sorted in non-decreasing order. |
| 30 | +-1000 <= target <= 1000 |
| 31 | +The tests are generated such that there is exactly one solution. |
| 32 | +''' |
| 33 | + |
| 34 | + |
| 35 | +# The Python Case (No Overflow) |
| 36 | +# Python's standard int type supports arbitrary-precision integers. This means they can grow to be as large as your machine's memory allows, unlike fixed-size integers in languages like C++ (int is typically 32-bit) or Java (int is 32-bit, long is 64-bit). |
| 37 | + |
| 38 | +class Solution: |
| 39 | + def twoSum(self, numbers: List[int], target: int) -> List[int]: |
| 40 | + if not numbers: |
| 41 | + return [-1,-1] |
| 42 | + left=0 |
| 43 | + right=len(numbers)-1 |
| 44 | + while left<right: |
| 45 | + k=numbers[left]+numbers[right] |
| 46 | + if k==target: |
| 47 | + return [left+1,right+1] |
| 48 | + elif k<target: |
| 49 | + left+=1 |
| 50 | + else: |
| 51 | + right-=1 |
| 52 | + return [-1,-1] |
| 53 | + |
| 54 | + |
| 55 | +# Complexity Analysis |
| 56 | +# Time complexity: O(n). |
| 57 | +# The input array is traversed at most once. Thus the time complexity is O(n). |
| 58 | + |
| 59 | +# Space complexity: O(1). |
| 60 | +# We only use additional space to store two indices and the sum, so the space complexity is O(1). |
0 commit comments