Leetcode 3sum closet

Source: Internet
Author: User

It uses the same idea as 3sum, and binary search. The key is pruning, but many mistakes have been made in pruning.

Then there was a faster idea O (N ^ 2 ).

#include<iostream>  #include <vector>  #include <algorithm>  #include <math.h>using namespace std;class Solution {public:int threeSumClosest(vector<int> &num, int target) {int minDis = 1 << 30;int closetSum = -1<<30;sort(num.begin(), num.end());for (int i = 0; i < num.size() - 2; i++){for (int j = i + 1; j < num.size() - 1; j++){int twoSum = num[i] + num[j];int value = target - twoSum;int tmpCloVal = searchValue(num, j + 1, num.size() - 1, value);if (abs(target - twoSum - tmpCloVal) < minDis){closetSum = twoSum + tmpCloVal;minDis = abs(target - closetSum);}if ( num[j+1]>0 && num[i]+num[j] > target)break;}if (num[i+1]>0 && num[i] > target)break;}return closetSum;}int searchValue(vector<int> num, int left, int right, int value){const int l = left, r = right;int closetVal;int m;if (value > num[right])return num[right];else if (value < num[left])return num[left];while (left <= right){m = (left + right) / 2;if (num[m] <= value && num[m + 1] >= value){break;}else if (num[m] < value){left = m + 1;}else{right = m - 1;}}closetVal = num[m];if (abs(closetVal-value) > abs(num[m + 1] - value)){closetVal = num[m+1];}if (abs(closetVal - value) > abs(num[m-1]-value)){closetVal = num[m - 1];}return closetVal;}};


Leetcode 3sum closet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.