Compared with others', mine can be improved significantly


  • 0
    F
    public int threeSumClosest(int[] nums, int target) {
        int result = 0;
        int min = Integer.MAX_VALUE;
        Arrays.sort(nums);
        int i = 0, n = nums.length;
        while (i <= n - 3) {
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                int cur = Math.abs(sum - target);
                if (cur < min) {
                    min = cur;
                    result = sum;
                }
                if (sum == target)
                    break;
                if (sum < target) {
                    j++;
                    while (j < k && nums[j] == nums[j - 1])
                        j++;
                }
                if (sum > target) {
                    k--;
                    while (j < k && nums[k] == nums[k + 1])
                        k--;
                }
            }
            i++;
            while (i <= n - 3 && nums[i] == nums[i - 1])
                i++;
        }
        return result;
    }

Log in to reply
 

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