Need to add some test case of 3sum closest.


  • 3
    M

    I initialize the variable closet which is used to store the closet value as Integer.MAX_VALUE / 2. This code was accepted.

    However I think if there is a test case which the target value is Integer.MAX_VALUE / 2 and all the combination of three number's sum is bigger or smaller than Integer.MAX_VALUE / 2, this code will return Integer.MAX_VALUE / 2 which is wrong. The right way to initialize the variable closet is using the value in the num[] like num[0] + num[1] + num[2].

    Also in the 3sum and 4sum should we have some overflow test case?

    public class Solution {
    	public int threeSumClosest(int[] num, int target) {
    		if (num == null || num.length < 3) {
    			return Integer.MAX_VALUE;
    		}
    		Arrays.sort(num);
    		int closet = Integer.MAX_VALUE / 2; // otherwise it will overflow for opeartion (closet-target)'
    		for (int i = 0; i < num.length - 2; i++) {
    			int left = i + 1;
    			int right = num.length - 1;
    			while (left < right) {
    				int sum = num[i] + num[left] + num[right];
    				if (sum == target) {
    					return sum;
    				} else if (sum < target) {
    					left++;
    				} else {
    					right--;
    				}
    				closet = Math.abs(sum - target) < Math.abs(closet - target) ? sum : closet;
    			}
    		}
    		return closet;
    	}
    }

Log in to reply
 

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