标签:
题目要求:
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).
题目地址:https://leetcode.com/problems/3sum-closest/
public class Solution { public static int threeSumClosest(int[] num, int target) { Arrays.sort(num); int sub=Integer.MAX_VALUE; int result=0; for(int i=0;i<num.length;i++){ int j=i+1,x=num.length-1; while(j<x){ int sum=num[i]+num[j]+num[x]; int temp_sub=sum>target?sum-target:target-sum; //sub=sub<temp_sub?sub:temp_sub; //System.out.println("current:"+num[i]+"&"+num[j]+"&"+num[x]+" sub="+sub); if(sub>temp_sub) { sub=temp_sub; result=sum; } if(num[i]+num[j]+num[x]>target){ x--; }else if(num[i]+num[j]+num[x]<target){ j++; }else{ x--;j++; } } } return result; } }
public class Solution { public static int threeSumClosest(int[] num, int target) { Arrays.sort(num); int sub=Integer.MAX_VALUE; int result=0; for(int i=0;i<num.length;i++){ int j=i+1,x=num.length-1; while(j<x){ int sum=num[i]+num[j]+num[x]; int temp_sub=sum>target?sum-target:target-sum; //sub=sub<temp_sub?sub:temp_sub; //System.out.println("current:"+num[i]+"&"+num[j]+"&"+num[x]+" sub="+sub); if(sub>temp_sub) { sub=temp_sub; result=sum; } if(num[i]+num[j]+num[x]>target){ x--; }else if(num[i]+num[j]+num[x]<target){ j++; }else{ x--;j++; } } } return result; } }
左右夹逼的思路,算Ksum时,前k-1个数都是循环套循环,最后k-1,k做左右夹逼,
夹逼过程,ia =k-1,ib=array.length-1
arrray[ia]+array[ib]>target ,ib--;
<,++;
==;找到等于target的,然后接着查找ia++,ib--
标签:
原文地址:http://www.cnblogs.com/charlesdoit/p/4333431.html