This problem is almost like 3sum. Actually it needs the same skip steps for j and k. But LeetCode did not put the test case there. So just put like this.
1 class Solution { 2 public: 3 int threeSumClosest(vector<int> &num, int target) { 4 int len = num.size(), result = num[0] + num[1] + num[2], i = 0, j = 0, k = 0; 5 sort(num.begin(), num.end()); 6 for (i = 0; i < len-2; i++) { 7 if (i > 0 && num[i] == num[i-1]) continue; 8 j = i+1, k = len-1; 9 while (j < k) { 10 int sum = num[i] + num[j] + num[k]; 11 if (fabs(sum - target) < fabs(result - target)) result = sum; 12 if (sum > target) k--; 13 else j++; 14 } 15 } 16 return result; 17 } 18 };