码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]3Sum Closest

时间:2015-02-28 01:33:12      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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;
}

  

[leetcode]3Sum Closest

标签:

原文地址:http://www.cnblogs.com/zhutianpeng/p/4304577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!