You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
5
+
Return the indices of the two numbers, index1 and index2, such that index1 < index2.
6
+
You must write an algorithm that runs in O(n) time complexity.
7
+
8
+
Example 1:
9
+
Input: numbers = [2,7,11,15], target = 9
10
+
Output: [1,2]
11
+
12
+
Explanation: Because numbers[0] + numbers[1] == 9, we return [1, 2].
13
+
14
+
Example 2:
15
+
Input: numbers = [2,3,4], target = 6
16
+
Output: [1,2]
17
+
'''
18
+
19
+
# Brute Force
20
+
# Time Complexity: O(n^2)
21
+
# Space Complexity: O(1)
22
+
23
+
'''
24
+
Below is the brute force solution.
25
+
It uses two nested loops to check all pairs of numbers in the array.
26
+
If a pair is found that sums to the target, it returns their indices.
27
+
'''
28
+
29
+
classSolution:
30
+
deftwoSum(self, numbers, target):
31
+
foriinrange(len(numbers)):
32
+
forjinrange(i+1,len(numbers)):
33
+
ifnumbers[i]+numbers[j]==target:
34
+
return [i+1,j+1]
35
+
return []
36
+
37
+
38
+
# Two Pointers
39
+
# Time Complexity: O(n)
40
+
# Space Complexity: O(1)
41
+
42
+
'''
43
+
Below is the two pointers solution.
44
+
It uses two pointers, one starting at the beginning of the array and the other at the end.
45
+
The pointers move towards each other until they find a pair of numbers that sum to the target.
46
+
If a pair is found, it returns their indices.
47
+
If the sum is less than the target, the left pointer is moved to the right.
48
+
If the sum is greater than the target, the right pointer is moved to the left.
0 commit comments