码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: 3Sum Closest

时间:2014-10-09 14:04:23      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   使用   ar   for   sp   

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

标签:style   blog   color   io   os   使用   ar   for   sp   

原文地址:http://www.cnblogs.com/EdwardLiu/p/4012459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!