File tree 2 files changed +41
-0
lines changed 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 21
21
13|[ Roman to Integer] ( ./0013-roman-to-integer.js ) |Easy|
22
22
14|[ Longest Common Prefix] ( ./0014-longest-common-prefix.js ) |Easy|
23
23
15|[ 3Sum] ( ./0015-3sum.js ) |Medium|
24
+ 16|[ 3Sum Closest] ( ./0016-3sum-closest.js ) |Medium|
24
25
17|[ Letter Combinations of a Phone Number] ( ./0017-letter-combinations-of-a-phone-number.js ) |Medium|
25
26
19|[ Remove Nth Node From End of List] ( ./0019-remove-nth-node-from-end-of-list.js ) |Medium|
26
27
20|[ Valid Parentheses] ( ./0020-valid-parentheses.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 16. 3Sum Closest
3
+ * https://leetcode.com/problems/3sum-closest/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an integer array nums of length n and an integer target, find three integers
7
+ * in nums such that the sum is closest to target.
8
+ *
9
+ * Return the sum of the three integers.
10
+ *
11
+ * You may assume that each input would have exactly one solution.
12
+ */
13
+
14
+ /**
15
+ * @param {number[] } nums
16
+ * @param {number } target
17
+ * @return {number }
18
+ */
19
+ var threeSumClosest = function ( nums , target ) {
20
+ const sums = new Set ( ) ;
21
+
22
+ nums . sort ( ( a , b ) => a - b ) ;
23
+
24
+ for ( let i = 0 ; i < nums . length - 2 ; i ++ ) {
25
+ let j = i + 1 ;
26
+ let k = nums . length - 1 ;
27
+
28
+ while ( j < k ) {
29
+ const sum = nums [ i ] + nums [ j ] + nums [ k ] ;
30
+ sums . add ( sum ) ;
31
+ if ( sum > target ) {
32
+ k -- ;
33
+ } else {
34
+ j ++ ;
35
+ }
36
+ }
37
+ }
38
+
39
+ return [ ...sums ] . reduce ( ( p , c ) => Math . abs ( c - target ) < Math . abs ( p - target ) ? c : p ) ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments