3 sum Java Solution O(n^2)


#1

Efficient Code

 public class Solution {
    public int threeSumClosest(int[] a, int b) {
        Arrays.sort(a);
        double  mindiff=a[0]+a[1]+a[a.length-1];
        int i=0;
        while(i<=a.length-3)
        {
            int j=i+1;
            int k=a.length-1;
            while(j<k)
            {
                double curr=a[i]+a[j]+a[k];
                if(curr>b) k--;
                else j++;
                if(Math.abs(curr-b)<Math.abs(mindiff-b))
                    mindiff=curr;
            }
            i++;
        }
        return  (int)mindiff;
        
    }
}