Leetcode–3Sum Closest

The Problem:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


  1. Fix one number first, look for the two sum up to a target. The n-sum questions all follow the same idea, break down to two sum. See 3 Sum.
  2. Record the minimum difference and result.

Java Solution:

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        int minDiff = Integer.MAX_VALUE;
        int result = 0;
        for(int first = 0; first< num.length-2; first++){
            int tar = target-num[first];
            int i = first+1;
            int j = num.length-1;
            while(i< j){
                    return target;
                else if(num[i] + num[j] < tar){
                    if(tar-num[i]-num[j] < minDiff){
                        minDiff = tar-num[i]-num[j];
                        result = num[first] + num[i]+num[j];
                else if(num[i] + num[j] > tar){
                    if(num[i]+num[j]-tar < minDiff){
                        minDiff = num[i]+num[j]-tar;
                        result = num[first] + num[i]+num[j];
        return result;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s