Skip to content

Commit c8b30b4

Browse files
committed
2824. Count Pairs Whose Sum is Less than Target
1 parent ec3a3b8 commit c8b30b4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2824. Count Pairs Whose Sum is Less than Target
5+
// Two Pointers
6+
7+
// Time complexity: O(n log n)
8+
// Space complexity: O(1)
9+
10+
func countPairs(_ nums: [Int], _ target: Int) -> Int {
11+
var count = 0
12+
var left = 0
13+
var right = nums.count - 1
14+
15+
let sortedNums = nums.sorted()
16+
17+
while left < right {
18+
if sortedNums[left] + sortedNums[right] < target {
19+
count += right - left
20+
left += 1
21+
} else {
22+
right -= 1
23+
}
24+
}
25+
26+
return count
27+
}
28+
}

0 commit comments

Comments
 (0)