Java solution , simple and easy to understand


  • 0
    K
    public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int min=Integer.MAX_VALUE;
            int res=0;
            for(int i=0;i<nums.length-2;i++){
                int low=i+1;
                int high = nums.length-1;
                while(low<high){
                    int tmp=nums[low]+nums[high]+nums[i];
                    if(tmp-target<0&&target>=0) {
                        if(target-tmp<min){min=target-tmp;res=tmp;}
                        low++;
                    }
                    else if(tmp-target>0&&target>=0) {
                        if(tmp-target<min){min=tmp-target;res=tmp;}
                        high--;
                    }
                    else if(tmp-target<0&&target<0) {
                        if(target-tmp<min){min=target-tmp;res=tmp;}
                        low++;
                    }
                    else if(tmp-target>0&&target<0){
                        if(tmp-target<min){min=tmp-target;res=tmp;}
                        high--;
                    }
                    else return target;
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.