Leetcode16:最接近的三数之和

Leetcode16:最接近的三数之和

问题描述

Leetcode16:最接近的三数之和_第1张图片

代码实现

package LeetCode;

import java.util.Arrays;

public class ThreeSumClosest
{

	public static void main(String[] args)
	{
		int target=1;
		int[] nums= {-1,2,1,-4};
		System.out.println(threeSumClosest(nums, target));

	}
	public static int threeSumClosest(int[]nums,int target)
	{
		int res=nums[0]+nums[1]+nums[nums.length-1];
		Arrays.sort(nums);
		for (int i = 0; i < nums.length-2; i++)
		{
			int start=i+1,end=nums.length-1;
			while (start<end)
			{
				int sum=nums[i]+nums[start]+nums[end];
				if (sum>target)
				{
					end--;
				}else {
					start++;
				}
				if (Math.abs(sum-target)<Math.abs(res-target))
				{
					res=sum;
				}
			}
		}
		return res;
	}

}

你可能感兴趣的:(算法)