mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Move to a different file since the input is sorted by default
This commit is contained in:
parent
68bb214bc0
commit
02f625f95a
2 changed files with 49 additions and 46 deletions
|
@ -131,49 +131,3 @@ nums = [3, 3]
|
|||
target = 6
|
||||
print(two_sum(nums, target))
|
||||
# => [0,1]
|
||||
|
||||
#
|
||||
# Approach 4: Two pointers
|
||||
#
|
||||
|
||||
# Complexity analysis
|
||||
|
||||
# Time complexity: O(n). Each of the n elements is visited at
|
||||
# most once, thus the time complexity is O(n).
|
||||
|
||||
# Space complexity: O(1). We only use two indexes, the space
|
||||
# complexity is O(1).
|
||||
|
||||
def two_sum(numbers, target)
|
||||
i = 0
|
||||
j = numbers.length - 1
|
||||
# note: sorting the array is important
|
||||
numbers = numbers.sort
|
||||
|
||||
while i < j
|
||||
sum = numbers[i] + numbers[j]
|
||||
|
||||
if target < sum
|
||||
j -= 1
|
||||
elsif target > sum
|
||||
i += 1
|
||||
else
|
||||
return [i, j]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
nums = [2, 7, 11, 15]
|
||||
target = 9
|
||||
print(two_sum(nums, target))
|
||||
# => [0,1]
|
||||
|
||||
nums = [2, 3, 4]
|
||||
target = 6
|
||||
print(two_sum(nums, target))
|
||||
# => [0,2]
|
||||
|
||||
nums = [-1, 0]
|
||||
target = -1
|
||||
print(two_sum(nums, target))
|
||||
# => [0,1]
|
||||
|
|
49
data_structures/arrays/two_sum_ii.rb
Normal file
49
data_structures/arrays/two_sum_ii.rb
Normal file
|
@ -0,0 +1,49 @@
|
|||
# Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
|
||||
|
||||
# Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
|
||||
|
||||
# You may assume that each input would have exactly one solution and you may not use the same element twice.
|
||||
|
||||
#
|
||||
# Approach 1: Two pointers
|
||||
#
|
||||
|
||||
# Complexity analysis
|
||||
|
||||
# Time complexity: O(n). Each of the n elements is visited at
|
||||
# most once, thus the time complexity is O(n).
|
||||
|
||||
# Space complexity: O(1). We only use two indexes, the space
|
||||
# complexity is O(1).
|
||||
|
||||
def two_sum(numbers, target)
|
||||
i = 0
|
||||
j = numbers.length - 1
|
||||
|
||||
while i < j
|
||||
sum = numbers[i] + numbers[j]
|
||||
|
||||
if target < sum
|
||||
j -= 1
|
||||
elsif target > sum
|
||||
i += 1
|
||||
else
|
||||
return [i, j]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
nums = [2, 7, 11, 15]
|
||||
target = 9
|
||||
print(two_sum(nums, target))
|
||||
# => [0,1]
|
||||
|
||||
nums = [2, 3, 4]
|
||||
target = 6
|
||||
print(two_sum(nums, target))
|
||||
# => [0,2]
|
||||
|
||||
nums = [-1, 0]
|
||||
target = -1
|
||||
print(two_sum(nums, target))
|
||||
# => [0,1]
|
Loading…
Reference in a new issue