Skip to content

Commit 4b025fe

Browse files
committed
15
1 parent 19bc19b commit 4b025fe

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

ruby/15-3Sum.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def three_sum(nums)
2+
sums = []
3+
nums.sort! # This is to get rid of duplicate solutions
4+
nums.each_with_index do |num, idx|
5+
next if idx.positive? && num == nums[idx - 1]
6+
7+
left = idx + 1
8+
right = nums.length - 1
9+
while left < right
10+
case num + nums[left] + nums[right] <=> 0
11+
when 1
12+
right -= 1
13+
when 0
14+
sums << [num, nums[left], nums[right]]
15+
left += 1
16+
left += 1 while nums[left] == nums[left - 1] && left < right
17+
when -1
18+
left += 1
19+
end
20+
end
21+
end
22+
sums
23+
end

0 commit comments

Comments
 (0)