Skip to content

Latest commit

 

History

History
34 lines (32 loc) · 914 Bytes

16. 3Sum Closest.md

File metadata and controls

34 lines (32 loc) · 914 Bytes

16. 3Sum Closest

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        //O(n3->n2)
        int res = 0;
        int dist = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for(int i = 0; i<nums.length; i++){
            int j = i+1; int k = nums.length-1;
            while(j<k){
                int sum = nums[i]+nums[j]+nums[k];
                if(sum==target) return target;
                else if(sum>target){
                    if(dist > (sum-target)){
                        dist = sum-target;
                        res = sum;
                    }
                    k--;
                }else{
                    if(dist > -(sum-target)){
                        dist = -(sum-target);
                        res = sum;
                    }
                    j++;
                }
            }
            
        }
        return res;
    }
}