• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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         int result = num[0] + num[1] + num[num.length - 1];
 4         Arrays.sort(num);
 5         for (int i = 0; i < num.length - 2; i++) {
 6             int start = i + 1, end = num.length - 1;
 7             while (start < end) {
 8                 int sum = num[i] + num[start] + num[end];
 9                 if (sum > target) {
10                     end--;
11                 } else {
12                     start++;
13                 }
14                 if (Math.abs(sum - target) < Math.abs(result - target)) {
15                     result = sum;
16                 }
17             }
18         }
19         return result;
20     }
21 }

 

第一遍做法:

 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 }

 

posted @ 2014-10-09 04:47  neverlandly  阅读(308)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3