LeetCode 3Sum Closest(016)解法總結

NewCoder1024發表於2020-03-28

描述

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

相關文章