Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 87cfe9a

Browse files
167. Two Sum II - Input Array Is Sorted
1 parent 888d391 commit 87cfe9a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
'''
2+
167. Two Sum II - Input Array Is Sorted
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.
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+
class Solution:
30+
def twoSum(self, numbers, target):
31+
for i in range(len(numbers)):
32+
for j in range(i+1,len(numbers)):
33+
if numbers[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.
49+
'''
50+
51+
class Solution:
52+
def twoSum(self, numbers, target):
53+
i=0
54+
j=len(numbers)-1
55+
56+
while i<=j:
57+
if numbers[i]+numbers[j]==target:
58+
return [i+1,j+1]
59+
elif numbers[i]+numbers[j]> target:
60+
j-=1
61+
else:
62+
i+=1
63+
return []
64+
65+
obj = Solution()
66+
numbers = [1,2,3,4]
67+
target = 3
68+
print(obj.twoSum(numbers, target))
69+
# Output: [1,2]
70+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /