Leetcode: 3sum closet

Source: Internet
Author: User

Question: For an array and a given target value, it is required to find three elements in the array. The sum of the three elements is the closest to the target value. Of course, it is the best.

Use the 3sum method to modify the condition.


int twoSum(vector
 
   &num, int start, int target){if(num.size() < 3 || start >= num.size())return -target;int head = start;int tail = num.size() - 1;int result = -target;int erro = 0x7fffffff;while (head < tail){int sum = num[head] + num[tail];if(sum == target){result = target;return target;    }else if(sum < target){do {++head;} while (head < tail && num[head] == num[head - 1]);}else{do {--tail;} while (tail > head && num[tail] == num[tail + 1]);}int curerro = abs(sum - target);if(curerro < erro){result = sum;erro = curerro;}}return result;}int threeSumClosest(vector
  
    &num, int target) {const int len = num.size();if(len < 3)return 0;sort(num.begin(), num.end());int closet = -target;int erro = 0x7fffffff;for (int i = 0; i < len - 2; ++i){int thisloop = twoSum(num, i + 1, target - num[i]);if(thisloop == target - num[i])return target;int cur_erro = abs(thisloop + num[i] - target);    if(cur_erro < erro)  {  closet = thisloop + num[i];  erro = cur_erro;}while(i + 1 < len && num[i + 1] == num[i]) ++i;}return 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.