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

3Sum Closest

时间:2014-09-15 10:06:18      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   os   java   ar   for   art   div   

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).

答案

public class Solution {
        public void swap(int[] array, int i, int j)
    {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }

    public void quickSort(int[] array, int start, int end)
    {
        if (start >= end)
        {
            return;
        }
        int middle = (start + end) / 2;
        swap(array, start, middle);
        int i = start + 1;
        while (i <= end)
        {
            if (array[i] >= array[start])
            {
                break;
            }
            i++ ;
        }
        int j = i + 1;
        for (; j <= end;)
        {
            while (j <= end)
            {
                if (array[j] < array[start])
                {
                    break;
                }
                j++ ;
            }
            if (j <= end)
            {
                swap(array, i, j);
                i++ ;
                j++ ;
            }
        }
        i-- ;
        if (array[i] < array[start])
        {
            swap(array, start, i);
        }
        quickSort(array, start, i - 1);
        quickSort(array, i + 1, end);
    }
    public int threeSumClosest(int[] num, int target) {
        int result=num[0]+num[1]+num[2];
        int diff=Math.abs(result-target);
        int sum;
        int newDiff;
        int i;
        int j;
        int k;
        quickSort(num,0,num.length-1);
        for(i=0;i<num.length-2;i++){
            j=i+1;
            k=num.length-1;
            while(j<k)
            {
                sum=num[i]+num[j]+num[k];
                newDiff=Math.abs(sum-target);
                if(newDiff<diff){
                    diff=newDiff;
                    result=sum;
                }
                if(sum<target)
                {
                    j++;
                }
                else{
                    k--;
                }
            }
        }
        return result;
    }
}


3Sum Closest

标签:style   color   io   os   java   ar   for   art   div   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39288681

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