public int threeSumClosest(int[] num, int target) {

    Arrays.sort(num);
    int closest = Integer.MAX_VALUE;
    int result = 0;

    for (int i = 0 ; i < num.length ; i++) {
      int head = i + 1;
      int tail = num.length - 1;

      while (head < tail) {
        int sum = num[i] + num[head] + num[tail];
        int diff = target - sum;

        if (diff == 0) {
          return sum;
        } else {
          if (Math.abs(diff) < closest) {
            closest = Math.abs(diff);
            result = sum;
          }
        }

        if (diff < 0) {
          tail--;
        } else {
          head++;
        }
      }
    }
    return result;
  }