0016_3Sum Closest

来源:互联网 发布:终结者4知乎 编辑:程序博客网 时间:2024/06/03 18:47

JAVA

在看过0015_3Sum的解题思路之后,本题作为练习,采用同样的思路进行运算。即使在看过3Sum之后,写代码时仍然有多处边界判断不准确,导致溢出或死循环。。。不过这种方法的效率还可以,大概排在前1/3左右。

public class Solution {    public int threeSumClosest(int[] nums, int target) {        Arrays.sort(nums);        int result = nums[0] + nums[1] + nums[2];        int temp;        for(int i = 0; i < nums.length - 2;){            for(int j = i+1, k = nums.length - 1; j < k;){                temp = nums[i] + nums[j] + nums[k];                if(Math.abs(temp - target) <= Math.abs(result - target)){                    result = temp;                    if(Math.abs(temp - target) == 0){                        return result;                    }                }                if(temp < target){                    ++j;                    while(j < k && nums[j] == nums[j-1]){                        ++j;                    }                }                if(temp > target){                    --k;                    while(j < k && nums[k] == nums[k+1]){                        --k;                    }                }            }            ++i;            while(i < nums.length && nums[i] == nums[i-1]){                ++i;            }        }        return result;    }}