-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_3sum.rb
More file actions
39 lines (31 loc) · 722 Bytes
/
15_3sum.rb
File metadata and controls
39 lines (31 loc) · 722 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
38
39
# frozen_string_literal: true
# https://leetcode.com/problems/3sum/
# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
nums.sort!
result = []
(0...nums.length - 2).each do |i|
curr = nums[i]
next if i.positive? && curr == nums[i - 1]
rem = -curr
start = i + 1
en = nums.length - 1
while start < en
s = nums[start]
e = nums[en]
if s + e == rem
result << [curr, s, e]
start += 1 while start < en && nums[start] == nums[start + 1]
en -= 1 while start < en && nums[en] == nums[en - 1]
start += 1
en -= 1
elsif s + e > rem
en -= 1
else
start += 1
end
end
end
result
end