JAVA-------------Easy Version To UnderStand!!!!!!!!!!!!


  • -1
    H
     public static  int threeSumClosest(int[] nums, int target) {
        int smallestGap=Integer.MAX_VALUE,finalSum=0;
        int len=nums.length;
        Arrays.sort(nums);
        for(int i=0;i<len;i++){
        	if(i>0&&nums[i]==nums[i-1])
        		continue;
        	int j=i+1,k=len-1;
        	while(j<k){
        		int partialSum=nums[i]+nums[j]+nums[k];
        		if(partialSum==target)
        			return target;
        		else if(partialSum>target){
        			if(partialSum-target<smallestGap){
        			smallestGap=partialSum-target;
        			finalSum=partialSum;
        			}
        			while(k>j&&nums[k]==nums[k-1])
        				k--;
        			k--;
        		}
        		else if(partialSum<target){
        			if(target-partialSum<smallestGap){
        			smallestGap=target-partialSum;
        			finalSum=partialSum;
        			}
        			while(j<k&&nums[j]==nums[j+1])
        				j++;
        			j++;
        		}		     		       			
        	}
        }     	
    	return finalSum;
    }

Log in to reply
 

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