Skip to content

Commit

Permalink
15
Browse files Browse the repository at this point in the history
  • Loading branch information
TedTran2019 committed Jul 8, 2022
1 parent 19bc19b commit 4b025fe
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions ruby/15-3Sum.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
def three_sum(nums)
sums = []
nums.sort! # This is to get rid of duplicate solutions
nums.each_with_index do |num, idx|
next if idx.positive? && num == nums[idx - 1]

left = idx + 1
right = nums.length - 1
while left < right
case num + nums[left] + nums[right] <=> 0
when 1
right -= 1
when 0
sums << [num, nums[left], nums[right]]
left += 1
left += 1 while nums[left] == nums[left - 1] && left < right
when -1
left += 1
end
end
end
sums
end

0 comments on commit 4b025fe

Please sign in to comment.