public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int min = 0;
        boolean firstMin = true;
        for (int i = 0; i < num.length - 2; i++) {
            int subTarget = target - num[i];
            int start = i + 1;
            int end = num.length - 1;
            int finalStart = start;
            int finalEnd = end;
            int preClosest = Math.abs(num[start] + num[end] - subTarget) + 1;

            while (start < end) {
                if (num[start] + num[end] < subTarget) {
                    finalStart = start;
                    int dis = Math.abs(num[start] + num[end] - subTarget);
                    if (dis <= preClosest) {
                        preClosest = dis;
                        start++;
                    } else {
                        break;
                    }
                } else if (num[start] + num[end] > subTarget) {
                    finalEnd = end;
                    int dis = Math.abs(num[start] + num[end] - subTarget);
                    if (dis <= preClosest) {
                        preClosest = dis;
                        end--;
                    } else {
                        break;
                    }
                } else {
                    finalEnd = end;
                    finalStart = start;
                    break;
                }
            }

            if (firstMin) {
                min = num[i] + num[finalStart] + num[finalEnd];
                firstMin = false;
            } else if (Math.abs(min - target) > Math.abs(target - (num[i] + num[finalStart] + num[finalEnd]))) {
                min = num[i] + num[finalStart] + num[finalEnd];
            }
        }
        return min;
    }