3Sum Closest | Java最短代码实现

原题链接: 16. 3Sum Closest

【思路】

3Sum 有点类似,都是先排序O(nlogn),再固定一个数nums[i],找出另两个(O(n2)。不同的是,题目已说明结果只有一个,

1.找到等于target的即可返回

2.用closest记录3Sum和target的绝对值,如果绝对值有减小,则更新sum。循环,最后返回sum即可:

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closest = 0x7fffffff;
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) i++;
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                closest = Math.min(Math.abs(sum - target), closest);
                if (closest == Math.abs(sum - target)) result = sum;
                if (sum == target) return target;
                else if (sum < target) left++;
                else right--;
            }
        }
        return result;
    }
120 / 120  test cases passed. Runtime: 14 ms  Your runtime beats 44.85% of javasubmissions.

欢迎优化!

你可能感兴趣的:(java,LeetCode,array)