[leetcode]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).
c代码:
#define INT_MAX 2147483647L /* maximum (signed) long value */ int Partition(int a[], int low, int high){ int pivotkey = a[low]; while(low < high){ while( 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; }