public static int threeSumClosest(int[] num, int target) {
    if (num.length < 3) return 0;
    Arrays.sort(num);
    int mid = 0;
    int last = num.length - 1;
    int closest = num[0] + num[1] + num[2];
    while (mid > 0) {
      while (mid < last) {
        int sum = num[mid];
        sum += num[last];
        for (int i = mid + 1; i < last; i++) {
          if (Math.abs(target - (num[i] + sum)) < Math.abs(target - closest)) {
            closest = num[i] + sum;
          }
        }
        int old = num[mid];
        while ( mid < last && num[mid] == old) mid++;
      }
      mid = 0;
      int old = num[mid];
      while (mid > 0 && num[mid] == old) mid--;
    }
    return closest;
  }