首页 > 代码库 > Leetcode: 3Sum Closest
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) { 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: 3Sum Closest
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。