10000 Update README.md · abroroo/leetcode@c3e95d7 · GitHub
[go: up one dir, main page]

Skip to content

Commit c3e95d7

Browse files
authored
Update README.md
1 parent f1ed046 commit c3e95d7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,43 @@ List is periodically updated
44

55
## LeetCode
66

7+
### #16. 3Sum Closest
8+
```
9+
const threeSumClosest = function(nums, target) {
10+
nums.sort((a, b) => a - b);
11+
12+
let closerSum = Infinity;
13+
14+
// there hould be two nums left for l, r pointers, so in total we have: i, l ,r : to sum up.
15+
for (let i = 0; i < nums.length - 2; i++) {
16+
// if [2,2,4,7,8] second two is skipped , not test 2 again for total sum
17+
if (i > 0 && nums[i] === nums[i - 1]) continue;
18+
19+
//since i started with 0, left is starting with i + 1
20+
let l = i + 1;
21+
// right is starting with last num, since i only comes till nums.length - 2
22+
let r = nums.length - 1
23+
24+
while (l < r) {
25+
let currentTotal = nums[i] + nums[l] + nums[r]
26+
if (currentTotal === target) return currentTotal
27+
// if for example target = 12, closerSum = 15 and currentTotal 17
28+
// then 3 < 5 and closerSum stays as it is because it's more closer to 12
29+
closerSum = Math.abs(target - closerSum) < Math.abs(target - currentTotal) ? closerSum : currentTotal
30+
31+
// move pointer to right if currentTotal is less than needed else move left
32+
if (currentTotal < target) {
33+
l++;
34+
} else {
35+
r--;
36+
}
37+
}
38+
}
39+
return closerSum
40+
}
41+
42+
43+
```
744
### #209 Minimum Size Sub Array
845

946
```

0 commit comments

Comments
 (0)
0