java 16. 3Sum Closest(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 16. 3Sum Closest(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        
        int len =  nums.length;
        if (len == 3)
            return nums[0] + nums[1] + nums[2];
        
        Arrays.sort(nums);
        int tLow, tHigh;
        tLow = target;
        tHigh = target + 1;
        
        while (true) {
            if (checkContains(nums, tLow))
                return tLow;
            if (checkContains(nums, tHigh))
                return tHigh;
            tLow--;
            tHigh++;
        }
    }
    
    private boolean checkContains(int[] nums, int target) {
        int len = nums.length;
        for (int i = 0; i < len - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int a, b, c;
            int low = i + 1, high = len - 1;
            a = nums[i];
            
            while (low < high) {
                b = nums[low];
                c = nums[high];
                if (a + b + c > target) {
                    high--;
                } else if (a + b + c < target) {
                    low++;
                } else {
                    return true;
                }
            }
        }
        return false;
    }
}
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
         int res = nums[0] + nums[1] + nums[2];
         Arrays.sort(nums);
         
         for (int i = 0; i < nums.length - 2; i++) {
             //element1 = nums[i];
             int j = i + 1;
             int k = nums.length - 1;
             while (j < k) {
                 int tempSum = nums[i] + nums[j] + nums[k];
                 if (tempSum == target) {
                     return target;
                 }else if (Math.abs(tempSum - target) < Math.abs(res - target)) {
                     res = tempSum;
                 }
                 if (tempSum > target) {
                     k--;
                 }else {
                     j++;
                 }
             }// while loop
         }//for loop
         return res;
         
    }
}

以上是关于java 16. 3Sum Closest(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 16. 3Sum Closest(#)。java

java 16. 3Sum Closest(#)。java

java 16. 3Sum Closest(#)。java

java 16. 3Sum Closest(#)。java

16. 3Sum Closest java solutions

16. 3Sum Closest