LeetCode 3Sum Closest(016)解法总结

392 阅读1分钟

描述

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).

思路

3Sum思路类似,但是要使用变化的target而不是0进行判断。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        List<Integer> temp = new LinkedList<>();
        int low_tar = target, high_tar = target;

        //当前的输出数组为空时,循环过不符合当前数值时,低目标进行自减,高目标进行自加
        while(temp.size() == 0){
            //当前的输出数组为空,遍历整个数组
            for(int i = 0; i<nums.length && temp.size() == 0; i++){
                //当前数据和上一个一样时忽略
                while(i != 0 && nums[i] == nums[i-1] && i<nums.length - 1){
                    i++;
                    continue;
                }
                int low = i+1, high = nums.length - 1;
                //在高低加数不相同时进行加和判断
                while(low < high){
                    if(nums[i] + nums[low] + nums[high] == low_tar || 
                       nums[i] + nums[low] + nums[high] == high_tar){
                        temp.add(nums[i]);
                        temp.add(nums[low]);
                        temp.add(nums[high]);
                        break;
                    }else if(nums[i] + nums[low] + nums[high] < low_tar){
                        low++;
                    }else{
                        high--;
                    }
                }
            }
            
            low_tar--;high_tar++;
        }
    return temp.get(0) + temp.get(1) + temp.get(2);
    }
}
Runtime: 4 ms, faster than 77.81% of Java online submissions for 3Sum Closest.
Memory Usage: 39.3 MB, less than 6.67% of Java online submissions for 3Sum Closest.

时间复杂度为O(n^3)。