Skip to content

Commit dc81394

Browse files
committed
2824
1 parent a93bab6 commit dc81394

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# @param {Integer[]} nums
2+
# @param {Integer} target
3+
# @return {Integer}
4+
def count_pairs(nums, target)
5+
count = 0
6+
(0...nums.size).each { |i|
7+
(i+1...nums.size).each { |j|
8+
count += 1 if nums[i] + nums[j] < target
9+
}
10+
}
11+
12+
count
13+
end
14+
15+
# sort + binary-search
16+
def count_pairs(nums, target)
17+
# the condition i < j does not matter (but the condition i < j, a < b will matter)
18+
# assume that we have pair a, b that a + b < target, at _i, _j respectively,
19+
# in case of a before b, we have i = _i < j = _j
20+
# in case if a after b, we have i = _j < j = _i
21+
# so we always can count pair (a,b) (a + b < target) no matter what the order of a, b is
22+
# so we can sort the nums and take advantage of it
23+
nums.sort!
24+
nums << Float::INFINITY
25+
count = 0
26+
(0...nums.size).each { |i|
27+
j = nums.bsearch_index { |x| x >= target - nums[i] }
28+
count += [i-1, j-1].min + 1 if j
29+
}
30+
31+
count
32+
end

0 commit comments

Comments
 (0)