3Sum Closest

LeetCode Q 16 - 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution

Code:

public int threeSumClosest(int[] nums, int target) {
	
	int res = 0, diff = Integer.MAX_VALUE;
	int len = nums.length;

	Arrays.sort(nums);

	for (int i = 0; i < len - 2; i++) {
		
		if (i != 0 && nums[i] == nums[i - 1]) continue;
		
		int l = i + 1, r = len - 1;
		
		while (l < r) {
			int sum = nums[i] + nums[l] + nums[r];
			if (Math.abs(sum - target) < diff) {
				diff = Math.abs(sum - target);
				res = sum;
			}
			
			if (sum > target)
				r--;
			else if (sum < target)
				l++;
			else if (sum == target)
				return target;
		}
	}
}

   Reprint policy


《3Sum Closest》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Valid Palindrome Valid Palindrome
LeetCode Q 125 - Valid PalindromeGiven a string, determine if it is a palindrome, considering only alphanumeric characte
2019-05-09 Tong Shi
Next 
Sort an Array Sort an Array
LeetCode Q 912 - Sort an ArrayGiven an array of integers nums, sort the array in ascending order. Example 1:Input: [5,2,
2019-05-09 Tong Shi
  TOC