17ms JAVA using sort short and easy understand


  • 1
    L
    public int threeSumClosest(int[] nums, int target) {
            if(nums.length==3) return nums[0]+nums[1]+nums[2];
            Arrays.sort(nums);
            int sum=0;
            int maxSum =nums[0]+nums[1]+nums[2];
            int idx =0,first=0,last=0;
            for(;idx<=nums.length-3;idx++){
            	first =idx+1;
            	last =nums.length-1;
            	while(first<last){
            		 sum = nums[idx]+nums[first]+nums[last];
            		 maxSum = Math.abs(target-maxSum)  >Math.abs(sum -target) ? sum: maxSum;
            		 if(sum >target)
            			 last--;
            		 else if(sum<target)
            			 first++;
            		 else return 0;
            	}
            }
            return maxSum;
        }

  • 0
    V

    it seems to me that maybe you want to return either sum or target if sum == target, instead of return 0.


Log in to reply
 

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