Created
January 23, 2019 16:34
-
-
Save bavernet/9442599e07d4f07a90d9d8a93dbb8af8 to your computer and use it in GitHub Desktop.
3Sum Closest Solution: O(N^2)
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
class Solution { | |
public: | |
int threeSumClosest(vector<int>& nums, int target) { | |
if (nums.size() < 3) | |
return 0; | |
int ans = nums[0] + nums[1] + nums[2]; | |
sort(nums.begin(), nums.end()); | |
for (int i = 0, n = nums.size(); i < n; ++i) { | |
int lo = i + 1, hi = n - 1; | |
while (lo < hi) { | |
int sum = nums[i] + nums[lo] + nums[hi]; | |
if (sum == target) | |
return target; | |
if (abs(sum - target) < abs(ans - target)) | |
ans = sum; | |
if (sum < target) ++lo; | |
else --hi; | |
} | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment