Topic:
Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has 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).
C Code:
#define INT_MAX 2147483647L/* Maximum (Signed) Long value */int Partition (int a[], int low, int. high) {int PIVOTK ey = A[low]; while (Low < high) {when (Low < high && A[high] >= pivotkey)--high; A[low]= A[high]; while (Low < high && A[low] <= pivotkey) ++low; A[high] = A[low]; } A[low] = PivotKey; return low;} void Qsort (int a[], int low, int. high) {int pivotloc; if (Low < high) {Pivotloc = Partition (A, low, high); Qsort (A, low, pivotloc-1); Qsort (A, Pivotloc + 1, high); }}void quiksort (int a[], int size) {Qsort (A, 0, size-1);} int threesumclosest (int *num, int n, int target) {int min = int_max,record,i; Quiksort (num, n); for (i = 0; i < n-2; i++) {int L = i + 1; int r = n-1; while (L < r) {int sum = Num[i] + num[l] + num[r]; if (sum = = target) {return sum; }else if (sum < target) {if (Target-sum < min) { record = sum; min = target-sum; } l++; }else{if (Sum-target < min) {record = sum; min = Sum-target; } r--; }} while (I+1<n-2 && num[i+1] = = Num[i]) i++; }return record;}
[Leetcode]3sum Closest