Created
April 23, 2019 08:16
-
-
Save bunnyadad/aad65597d94587b524aac069884c6d6f to your computer and use it in GitHub Desktop.
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
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
class Solution { | |
public: | |
int threeSumClosest(vector<int> nums, int target) | |
{ | |
if (nums.size() < 3) return target; | |
sort(nums.begin(), nums.end()); | |
int closest = nums[0] + nums[1] + nums[2]; | |
for (size_t i = 0; i < nums.size() - 2; i++) | |
{ | |
int font = i + 1; | |
int back = nums.size() - 1; | |
while (font < back) | |
{ | |
int sum = nums[i] + nums[font] + nums[back]; | |
if (sum == target) return target; | |
if (abs(sum - target) < abs(closest - target)) closest = sum; | |
if (sum > target) back--; | |
else font++; | |
} | |
} | |
return closest; | |
} | |
}; | |
int main() | |
{ | |
Solution a; | |
auto b = a.threeSumClosest({ 1, 2, 4, 8, 16, 32, 64, 128 }, 82); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment