Skip to content

Commit 34bce6d

Browse files
committed
Add solution #259
1 parent 8514d22 commit 34bce6d

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@
248248
256|[Paint House](./solutions/0256-paint-house.js)|Medium|
249249
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
250250
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
251+
259|[3Sum Smaller](./solutions/0259-3sum-smaller.js)|Medium|
251252
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
252253
263|[Ugly Number](./solutions/0263-ugly-number.js)|Easy|
253254
264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium|

solutions/0259-3sum-smaller.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 259. 3Sum Smaller
3+
* https://leetcode.com/problems/3sum-smaller/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of n integers nums and an integer target, find the number of index triplets
7+
* i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @param {number} target
13+
* @return {number}
14+
*/
15+
var threeSumSmaller = function(nums, target) {
16+
nums.sort((a, b) => a - b);
17+
const n = nums.length;
18+
let result = 0;
19+
20+
for (let i = 0; i < n - 2; i++) {
21+
let left = i + 1;
22+
let right = n - 1;
23+
24+
while (left < right) {
25+
const sum = nums[i] + nums[left] + nums[right];
26+
if (sum < target) {
27+
result += right - left;
28+
left++;
29+
} else {
30+
right--;
31+
}
32+
}
33+
}
34+
35+
return result;
36+
};

0 commit comments

Comments
 (0)