Leetcode's 16_3sum closest

Source: Internet
Author: User
Tags abs

Original title:

Given an array S of n integers, find three integers in s such so the sum is closest to a Given number, target. Return the sum of the three integers. You may assume this each input would have exactly one solution.

    For example, given array S = {-1 2 1-4}, and target = 1.

    The sum is closest to the target is 2. (-1 + 2 + 1 = 2).

The analysis:

And the 3sum similar to the question number 15, but this problem requires three numbers and is a given number, that is, find a+b+c=target, solve the same ideas, the two number of the sum of the target into target-a can.


Problem-Solving Code:

For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2.

(-1 + 2 + 1 = 2). Finds three digits from the given array, which is closest to the given target #include <iostream> #include <vector> #include <algorithm> using


namespace Std; Class Solution {public:int threesumclosest (vector<int>& nums, int target) {if (Nums.size () <3) {RE
		turn-1;
		int tarsum = 0;
		int tempsum = 0;
		int nmin = 1024;

		int nret = 0;  Sort (Nums.begin (), Nums.end ());  Causes the number in the container to be an ordered sequence for (int i=0; I<nums.size ()-2; i++) {tarsum = target-nums[i];//Declare the target of the search and A+b+c = targets, a+b =  target-c int j = i+1;

			Declares the search for the end-node int k=nums.size ()-1;

				while (j<k) {tempsum = Nums[j]+nums[k]-tarsum;
					if (ABS (TempSum) < nmin) {nmin = ABS (TempSum);
				Nret = Nums[i]+nums[j]+nums[k];
				} if (TempSum < 0) {j + +;
				else if (TempSum > 0) {k--; else if (tempsum = 0) {return TARget;
	}} return nret;
 }
};


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.