File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } nums
3+ * @param {number } target
4+ * @return {number }
5+ */
6+ let threeSumClosest = function ( nums , target ) {
7+ let n = nums . length
8+ if ( n === 3 ) {
9+ return getSum ( nums )
10+ }
11+ // 先升序排序 此为解题的前置条件
12+ nums . sort ( ( a , b ) => a - b )
13+
14+ let min = Infinity // 和 target 的最小差
15+ let res
16+
17+ // 从左往右依次尝试定一个基础指针 右边至少再保留两位 否则无法凑成3个
18+ for ( let i = 0 ; i <= nums . length - 3 ; i ++ ) {
19+ let basic = nums [ i ]
20+ let left = i + 1 // 左指针先从 i 右侧的第一位开始尝试
21+ let right = n - 1 // 右指针先从数组最后一项开始尝试
22+
23+ while ( left < right ) {
24+ let sum = basic + nums [ left ] + nums [ right ] // 三数求和
25+ // 更新最小差
26+ let diff = Math . abs ( sum - target )
27+ if ( diff < min ) {
28+ min = diff
29+ res = sum
30+ }
31+ if ( sum < target ) {
32+ // 求出的和如果小于目标值的话 可以尝试把左指针右移 扩大值
33+ left ++
34+ } else if ( sum > target ) {
35+ // 反之则右指针左移
36+ right --
37+ } else {
38+ // 相等的话 差就为0 一定是答案
39+ return sum
40+ }
41+ }
42+ }
43+
44+ return res
45+ }
46+
47+ function getSum ( nums ) {
48+ return nums . reduce ( ( total , cur ) => total + cur , 0 )
49+ }
You can’t perform that action at this time.
0 commit comments