Title Requirements:
Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Title Address: https://leetcode.com/problems/3sum-closest/
Public classSolution { Public Static intThreesumclosest (int[] num,inttarget) {arrays.sort (num); intsub=Integer.max_value; intResult=0; for(inti=0;i<num.length;i++){ intJ=i+1,x=num.length-1; while(j<x) { intsum=num[i]+num[j]+Num[x]; inttemp_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++; } } } returnresult; }}
Public classSolution { Public Static intThreesumclosest (int[] num,inttarget) {arrays.sort (num); intsub=Integer.max_value; intResult=0; for(inti=0;i<num.length;i++){ intJ=i+1,x=num.length-1; while(j<x) { intsum=num[i]+num[j]+Num[x]; inttemp_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++; } } } returnresult; }}
Left and right to clamp the idea, calculate ksum, the number of front k-1 is circulating sleeve cycle, the last k-1,k to do pinch,
Clamping process, IA =k-1,ib=array.length-1
Arrray[ia]+array[ib]>target, ib--;
<,++;
= =; Find equals target, then search for ia++,ib--
Leetcode:3sum Closest