[LeetCode] 16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Thought process:
Sort the array. Iterate through the array. As we iterate, use two pointers: one from start, one from end, to iterate through the array. Use a global variable to keep track of closest sum.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closest = target + Integer.MAX_VALUE;
        
        for (int i = 0; i < nums.length; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            
            while (start < end) {
                int threeSum = nums[i] + nums[start] + nums[end];
                int difference = Math.abs(threeSum - target);
          
                if (difference < Math.abs(closest - target)) {
                    closest = threeSum;
                }
                if (threeSum < target) {
                    start++;
                } else {
                    end--;
                }
            }
        }
        
        return closest;
    }
}

Time complexity:
Sorting takes O(nlogn). Loop takes O(n^2). The overall time complexity is O(n^2).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula