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

        int record = 0;
        int min = Integer.MAX_VALUE;
        int length = num.length;

        Arrays.sort(num);

        for (int i = 0; i < length; i++) {
            //except num[0], start is the second number, end is the last number
            int start = i + 1;
            int end = length - 1;

            while (start < end) {
                //get the sum
                int sum = num[i] + num[start] + num[end];
                //the same, samply return
                if (sum == target) {
                    min = 0;
                    record = sum;
                    break;
                }
                //less than, move the start, add bigger number
                if (sum < target) {
                    //if the min is not the smaller, change the min, and record the sum
                    if (target - sum < min) {
                        min = target - sum;
                        record = sum;
                    }
                    start++;
                } //bigger than, move the end, add smaller number
                else if (sum > target) {
                    //if the min is not the smaller, change the min, and record the sum
                    if (sum - target < min) {
                        min = sum - target;
                        record = sum;
                    }
                    end--;
                }
            }
            //avoid the duplicate number
            while (i < length - 1 && num[i] == num[i + 1]) {
                i++;
            }
        }
        return record;
    }