leetcode-3Sum Closest
int cmp(const void *a,const void *b){ return *(int *)a-*(int *)b; } int threeSumClosest(int* num, int numsSize, int target) { qsort(num,numsSize,sizeof(num[0]),cmp); int ret; int min_err=-1; for(int i=0; i<numsSize; i++){ if (i > 0 && num[i]==num[i-1]) continue; int j,k; j = i+1; k = numsSize-1; while (j<k) { if (j>i+1 && num[j]==num[j-1]) { j++; continue; } if (k<numsSize-1 && num[k]==num[k+1]) { k--; continue; } int err = num[i] + num[j] + num[k]-target; if (min_err==-1||abs(err)<min_err) { min_err=abs(err); ret=num[i] + num[j] + num[k]; if(err==0) return ret; } if(err>0){ k--; }else{ j++; } } } return ret; }