题解 | #最接近的三数之和#
最接近的三数之和
https://www.nowcoder.com/practice/f889497fd1134af5af9de60b4d13af23
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param target int整型 * @return int整型 */ function ClosestSum( nums , target ) { // write code here // 先组合 let count ; let len = nums.length; let fun = function fun(n,m,arr,result=[]){ for(let i = n;i>=m;i--){ result[m-1] = arr[i-1] if(m>1){ fun(i-1,m-1,arr,result) } let sk = result.reduce((pre,next)=>pre+next); if(count===undefined){ count=sk }else{ //找出绝对值最小的值 if(Math.abs(target - sk )<Math.abs(target - count )){ count = sk } } } } fun(len,3,nums); return count } module.exports = { ClosestSum : ClosestSum };