Skip to content

Commit 44bbbd8

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 16.6 MB (62.67%)
1 parent a55c860 commit 44bbbd8

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, return <em>the number of pairs</em> <code>(i, j)</code> <em>where</em> <code>0 &lt;= i &lt; j &lt; n</code> <em>and</em> <code>nums[i] + nums[j] &lt; target</code>.
2+
<p>&nbsp;</p>
3+
<p><strong class="example">Example 1:</strong></p>
4+
5+
<pre>
6+
<strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
7+
<strong>Output:</strong> 3
8+
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
9+
- (0, 1) since 0 &lt; 1 and nums[0] + nums[1] = 0 &lt; target
10+
- (0, 2) since 0 &lt; 2 and nums[0] + nums[2] = 1 &lt; target
11+
- (0, 4) since 0 &lt; 4 and nums[0] + nums[4] = 0 &lt; target
12+
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
13+
</pre>
14+
15+
<p><strong class="example">Example 2:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
19+
<strong>Output:</strong> 10
20+
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
21+
- (0, 1) since 0 &lt; 1 and nums[0] + nums[1] = -4 &lt; target
22+
- (0, 3) since 0 &lt; 3 and nums[0] + nums[3] = -8 &lt; target
23+
- (0, 4) since 0 &lt; 4 and nums[0] + nums[4] = -13 &lt; target
24+
- (0, 5) since 0 &lt; 5 and nums[0] + nums[5] = -7 &lt; target
25+
- (0, 6) since 0 &lt; 6 and nums[0] + nums[6] = -3 &lt; target
26+
- (1, 4) since 1 &lt; 4 and nums[1] + nums[4] = -5 &lt; target
27+
- (3, 4) since 3 &lt; 4 and nums[3] + nums[4] = -9 &lt; target
28+
- (3, 5) since 3 &lt; 5 and nums[3] + nums[5] = -3 &lt; target
29+
- (4, 5) since 4 &lt; 5 and nums[4] + nums[5] = -8 &lt; target
30+
- (4, 6) since 4 &lt; 6 and nums[4] + nums[6] = -4 &lt; target
31+
</pre>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>1 &lt;= nums.length == n &lt;= 50</code></li>
38+
<li><code>-50 &lt;= nums[i], target &lt;= 50</code></li>
39+
</ul>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Approach: Two Pointer
2+
3+
# Time: O(n log n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def countPairs(self, nums: List[int], target: int) -> int:
8+
nums.sort()
9+
count = 0
10+
left, right = 0, len(nums) - 1
11+
12+
while left < right:
13+
if (nums[left] + nums[right]) < target:
14+
count += right - left
15+
left += 1
16+
else:
17+
right -= 1
18+
19+
return count
20+

0 commit comments

Comments
 (0)