[LeetCode] 16. 3Sum Closest (Java)

2023. 1. 11. 09:21알고리즘/LeetCode

Description

Given an integer array nums of length n 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.

 

target과 가장 가까운 세 정수의 합을 구하기.

 

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Example 2:

Input: nums = [0,0,0], target = 1
Output: 0
Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).

 

Constraints:

  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -104 <= target <= 104

Solution

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = nums[0]+nums[1]+nums[2], sum, dif1, dif2;
        
        for(int i=0;i<nums.length-2;i++){
            int j=i+1;
            int k=nums.length-1;
            
            while(j<k){
                sum = nums[i] + nums[j] + nums[k];
                
                dif1 = target - ans;
                if(dif1 < 0) dif1 = -dif1;
                
                dif2 = target - sum;
                if(dif2 < 0) dif2 = -dif2;
                
                if(dif1>=dif2) ans = sum;
                
                if(target-sum >= 0) j++;
                if(target-sum <= 0) k--;
                
                if(ans == target) break;
            }
        }
        return ans;
    }
}

이전 문제 3Sum과 같은 방식으로 합을 구하고 target과 근접한 값에 대한 조건을 넣어주었다.