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

问题分析:问题同3Sums,即转化为2Sum的基本问题,这里添加了一个标志进行记录最小差距的值即可;

代码:

public class Solution {
    public int threeSumClosest(int[] num, int target) {
		/****处理边界值情况*****/
        if(num == null || num.length == 0)
			return 0;
		int result = 0;
		
		if(num.length <= 3)
		{
			for(int data : num)
				result += data;
			return result;
		}
		//先进行一次排序
		quickSort(num, 0 , num.length - 1);
		//Arrays.sort(num);
		
		int min_distance = Integer.MAX_VALUE;//记录与目标值之间的最小值
		int temp_target = 0;//当前的目标值
		int temp_distance = 0;
		
		for(int i = 0; i < num.length - 2; i++)
		{
			temp_target = target - num[i];
			int start = i + 1;
			int end = num.length - 1;
			
			while(start < end)
			{
				int temp_sum = num[start] + num[end];
				if(temp_sum == temp_target)
				{
					return target;
				}
				else if(temp_sum < temp_target)
				{
					++start;
					temp_distance = temp_target - temp_sum;
				}
				else
				{
					--end;
					temp_distance = temp_sum - temp_target;
				}
				
				if(temp_distance < min_distance)
				{
					min_distance = temp_distance;
					result = temp_sum + num[i];
				}
			}
		}
		
		return result;
		
    }
	
	/*先写快速排序*/
	private void quickSort(int[] data,int start,int end)
	{
		if(start < end)
		{
			int mid = partition(data, start, end);
			quickSort(data, start, mid - 1);
			quickSort(data,mid + 1, end);
		}
	}
		
	private int partition(int[] data, int start,int end)
	{
		int mid_data = data[end];//选取哨兵
		int index = start;
		
		for(int i = start; i < end; i++)
		{
			if(data[i] < mid_data)
			{
				swap(data, index, i);
				++ index;
			}
		}
		swap(data, index, end);
		return index;
	}
	
	//交换数组中的两个值数据
	private void swap(int[] data, int a, int b)
	{
		int temp = data[a];
		data[a] = data[b];
		data[b] = temp;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值