An easy 3Sum-based solution


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

Log in to reply
 

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