-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_numbers.py
More file actions
37 lines (30 loc) · 894 Bytes
/
find_numbers.py
File metadata and controls
37 lines (30 loc) · 894 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def findTwoNumbers(self, nums, target):
"""
- array is sorted
- nums[l] + nums[r]
- more than target, move r pointer backwards
- less than target, move l pointer forward
- if equal to target, append to result array
"""
if not nums:
return []
l, r = 0, len(nums) - 1
while l < r:
total = nums[l] + nums[r]
if total < target:
l += 1
elif total > target:
r -= 1
else:
return [l, r]
# Time Complexity: O(n)
# Space Complexity: O(1)
if __name__ == "__main__":
solution = Solution()
nums = [1, 2, 3, 4, 6]
target = 6
result = solution.findTwoNumbers(nums, target)
assert result == [1, 3]
print(result)
print("Test Case Passed!")