Skip to content

Commit

Permalink
Solve: 3Sum Closest
Browse files Browse the repository at this point in the history
  • Loading branch information
fkdl0048 committed Sep 29, 2024
1 parent 0f9908a commit 656b261
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"files.associations": {
"*.yarnproject": "jsonc",
"iostream": "cpp",
"vector": "cpp"
"vector": "cpp",
"xlocale": "cpp"
},
"C_Cpp.errorSquiggles": "disabled"
}
28 changes: 28 additions & 0 deletions 2024/LeetCode/3Sum Closest.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();

sort(nums.begin(), nums.end());
int closestSum = nums[0] + nums[1] + nums[2];

for (int i = 0; i < n - 2; i++){
int left = i + 1;
int right = n - 1;

while (left < right){
int currentSum = nums[i] + nums[left] + nums[right];

if (abs(currentSum - target) < abs(closestSum - target))
closestSum = currentSum;

if (currentSum < target)
left++;
else
right--;
}
}

return closestSum;
}
};

0 comments on commit 656b261

Please sign in to comment.