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

这道题跟3Sum很像,区别就是要维护一个最小的diff,求出和目标最近的三个和。brute force时间复杂度为O(n^3),优化的解法是使用排序之后夹逼的方法,总的时间复杂度为O(n^2+nlogn)=(n^2),空间复杂度是O(n)。

第二遍做法:

 1 public class Solution {

 2     public int threeSumClosest(int[] num, int target) {

 3         if (num == null || num.length < 3) return 0;

 4         Arrays.sort(num);

 5         int minDiff = num[0] + num[1] + num[2] - target;

 6         int diff = 0;

 7         for (int i=num.length-1; i>=2; i--) {

 8             if (i<num.length-1 && num[i]==num[i+1]) continue;

 9             diff = twoSumClosest(num, 0, i-1, target-num[i]);

10             if (Math.abs(diff) < Math.abs(minDiff)) {

11                 minDiff = diff;

12             }

13         }

14         return minDiff + target;

15     }

16     

17     public int twoSumClosest(int[] num, int l, int r, int tar) {

18         int minDif = num[l] + num[r] - tar;

19         int dif = 0;

20         while (l < r) {

21             dif = num[l] + num[r] - tar;

22             if (dif == 0) return dif;

23             if (Math.abs(dif) < Math.abs(minDif)) {

24                 minDif = dif;

25             }

26             if (dif < 0) {

27                 l++;

28             }

29             else {

30                 r--;

31             }

32         }

33         return minDif;

34     }

35 }

第一遍做法:

 1 public class Solution {

 2     public int threeSumClosest(int[] num, int target) {

 3         if (num==null || num.length<3) {

 4             return Integer.MIN_VALUE;

 5         }

 6         int res = num[0] + num[1] + num[2] - target;

 7         Arrays.sort(num);

 8         for (int i=num.length-1; i>=2; i--) {

 9             int cur = twoSum(num, target-num[i], 0, i-1);

10             if (Math.abs(cur) < Math.abs(res)) {

11                 res = cur;

12             }

13         }

14         return target+res;

15     }

16     

17     public int twoSum(int[] num, int target, int l, int r) {

18         int closest = num[l] + num[r] - target;

19         while (l < r) {

20             if (num[l] + num[r] == target) {

21                 return 0;

22             }

23             int diff = num[l] + num[r] - target;

24             if (Math.abs(diff) < Math.abs(closest)) {

25                 closest = diff;

26             }

27             if (num[l] + num[r] > target) {

28                 r--;

29             }

30             else {

31                 l++;

32             }

33         }

34         return closest;

35     }

36 }

 

你可能感兴趣的:(LeetCode)