My shared JAVA solution with O(1) space complexity


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

  • 0
    G

    Need to modify the above method to like this:

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

Log in to reply
 

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