A 17 ms Java solution


  • 0
    D
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int subMin = Math.abs(nums[len - 1] + nums[len - 2] + nums[len - 3] - target);
        int sub;
        int closestNum = nums[len - 1] + nums[len - 2] + nums[len - 3];
        int lo;
        int hi;
        int sum;
        int loTemp = 0;
        int hiTemp = 0;
        for (int i = 0; i < nums.length - 2; i++) {
            if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
                lo = i + 1;
                hi = nums.length - 1;
                sum = target - nums[i];
                while (lo < hi) {
                    loTemp = lo;
                    hiTemp = hi;
                    if (nums[lo] + nums[hi] == sum) {
                        return target;
                    } else if (nums[lo] + nums[hi] < sum) {
                        lo++;
                        if (nums[lo] + nums[hi] > sum) {
                            sub = Math.abs(nums[i] + nums[lo] + nums[hi] - target);
                            if (sub <= subMin) {
                                subMin = sub;
                                closestNum = nums[i] + nums[lo] + nums[hi];
                            }
                            sub = Math.abs(nums[i] + nums[lo - 1] + nums[hi] - target);
                            if (sub <= subMin) {
                                subMin = sub;
                                closestNum = nums[i] + nums[lo - 1] + nums[hi];
                            }
                        }
                    } else {
                        hi--;
                        if (nums[lo] + nums[hi] < sum) {
                            sub = Math.abs(nums[i] + nums[lo] + nums[hi] - target);
                            if (sub <= subMin) {
                                subMin = sub;
                                closestNum = nums[i] + nums[lo] + nums[hi];
                            }
                            sub = Math.abs(nums[i] + nums[lo] + nums[hi + 1] - target);
                            if (sub <= subMin) {
                                subMin = sub;
                                closestNum = nums[i] + nums[lo] + nums[hi + 1];
                            }
                        }
                    }
                }
            }
            sub = Math.abs(nums[i] + nums[loTemp] + nums[hiTemp] - target);
            if (sub <= subMin) {
                subMin = sub;
                closestNum = nums[i] + nums[loTemp] + nums[hiTemp];
            }
        }
        
        return closestNum;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.