Created
July 23, 2021 03:57
-
-
Save ravitejamuddada/b56c373f77f76eded4eb7f05c554149c to your computer and use it in GitHub Desktop.
leetcode 3sum closest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Input: nums = [-1,2,1,-4], target = 1 | |
Output: 2 | |
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). | |
*/ | |
//------------------------------------------------------------------- | |
/** | |
* @param {number[]} nums | |
* @param {number} target | |
* @return {number} | |
*/ | |
var threeSumClosest = function(nums, target) { | |
nums.sort((a,b)=>a-b); | |
const len=nums.length; | |
let closest=nums[0]+nums[1]+nums[len-1]; | |
for(let i=0;i<len-2;i++){ | |
let j=i+1; | |
let k=len-1; | |
while(j<k){ | |
let sum=nums[i]+nums[j]+nums[k]; | |
if(sum<=target) j++; | |
else if(sum>target) k--; | |
if(Math.abs(closest - target) > Math.abs(sum - target)){ | |
closest=sum; | |
} | |
} | |
} | |
return closest; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment