【leetcode】3Sum Closest

3Sum Closest

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).
 
与 3Sum类似,只是需要添加一个变量distance,用来记录和target距离最小的a+b+c
 
 1 class Solution {

 2 public:

 3     int threeSumClosest(vector<int> &num, int target) {

 4        

 5         int n=num.size();

 6         sort(num.begin(),num.end());

 7        

 8         int i,j,k;

 9         int a,b,c;

10         int result;

11         int distance=INT_MAX;

12        

13         for(i=0;i<n-2;i++)

14         {

15             j=i+1;

16             k=n-1;

17            

18             while(j<k)

19             {

20                 a=num[i];

21                 if(i>0&&num[i]==num[i-1])

22                 {

23                     break;

24                 }

25                 b=num[j];

26                 if(j>i+1&&num[j]==num[j-1])

27                 {

28                     j++;

29                     continue;

30                 }

31                

32                 c=num[k];

33                 if(k<n-1&&num[k]==num[k+1])

34                 {

35                     k--;

36                     continue;

37                 }

38                

39                 if(a+b+c==target)

40                 {

41                     return target;

42                 }

43                 else if(a+b+c<target)

44                 {

45                     if(target-(a+b+c)<distance)

46                     {

47                         result=a+b+c;

48                         distance=target-result;

49                     }

50                     j++;

51                 }

52                 else if(a+b+c>target)

53                 {

54                     if((a+b+c)-target<distance)

55                     {

56                         result=a+b+c;

57                         distance=result-target;

58                     }

59                     k--;

60                 }

61             }

62         }

63        

64         return result;

65  

66        

67     }

68 };

 

你可能感兴趣的:(LeetCode)