LeetCode : 3Sum Closest

来源:互联网 发布:a星算法怎么算线性袋鼠 编辑:程序博客网 时间:2024/04/28 06:20

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).


class Solution {public:    int threeSumClosest(vector<int> &num, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int n = num.size();          if(n ==0 )return 0;          vector<int> tuple(3);          sort(num.begin(), num.end());          int min = abs(num[0] + num[1] + num[2] - target);        tuple[0] = num[0];        tuple[1] = num[1];        tuple[2] = num[2];        int val = num[0] - 1;          for(int i = 0 ;i < n - 2; ++i){              int j = i + 1;              int k = n-1;              if(num[i] == val)                  continue;              val = num[i];              while(j < k ){                  int temp = abs(num[i] + num[j] + num[k] - target);                if(temp < min){                      tuple[0] = num[i];                      tuple[1] = num[j];                      tuple[2] = num[k];                      min = temp;                }                  if(temp == 0){                    break;                }                if(num[i] + num[j] + num[k] > target){                      --k;                  }                  else{                      ++j;                  }              }          }          return tuple[0] + tuple[1] + tuple[2];      }};


原创粉丝点击