O(n^2) Solution, Java


  • 0
    V
    public class Solution {
        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            
            int res = 0, diff = Integer.MAX_VALUE;
            for (int i = 0; i < nums.length - 2; i++) {
                int t = target - nums[i];
                int start = i + 1, end = nums.length - 1;
                
                while(start < end) {
                    int sum = nums[start] + nums[end];
                    if (Math.abs(sum - t) < diff) {
                        res = sum + nums[i];
                        diff = Math.abs(sum - t);
                    }
                    if (sum > t) end--;
                    else start++;
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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