-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0259-3sum-smaller.js
More file actions
36 lines (32 loc) · 805 Bytes
/
0259-3sum-smaller.js
File metadata and controls
36 lines (32 loc) · 805 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
/**
* 259. 3Sum Smaller
* https://leetcode.com/problems/3sum-smaller/
* Difficulty: Medium
*
* Given an array of n integers nums and an integer target, find the number of index triplets
* i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumSmaller = function(nums, target) {
nums.sort((a, b) => a - b);
const n = nums.length;
let result = 0;
for (let i = 0; i < n - 2; i++) {
let left = i + 1;
let right = n - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum < target) {
result += right - left;
left++;
} else {
right--;
}
}
}
return result;
};