[Leetcode 46] 16 3 Sum Cloest

Problem:

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

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

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

Analysis:

It's very much like 3 Sum problem. But instead having 0 as the 3 elements' sum, we have a given target as sum. And inorder to keep the cloest, we also need extra variables to keep track of the current cloest sum. What's simplified is that we can ignore the duplicate elements which are very important in 3 Sum problem.

Code:

 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int> &num, int target) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         sort(num.begin(), num.end());
 7         
 8         int diff = 0x7fffffff;
 9         int sum = 0;
10         for (int n=0; n<num.size(); n++) {
11             int i=n+1, j = num.size()-1;
12             while (i < j) {
13                 int f = num[i] + num[j] + num[n];
14                 
15                 if (f == target) {
16                     return f;
17                 } else if (f > target) {
18                     if ((f-target) < diff) {
19                         diff = f-target;
20                         sum = f;
21                     }
22                     j--;
23                 } else if (f < target){ // f < d
24                     if ((target-f) < diff) {
25                         diff = target-f;
26                         sum = f;
27                     }
28                     i++;
29                 }
30             }
31         }
32         
33         return sum;
34         
35     }
36 };
View Code

Attention:

原文地址:https://www.cnblogs.com/freeneng/p/3098433.html