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).
解决思路:

我们可以在 2sum问题 的基础上来解决3sum问题,假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。
我们以选第一个和第二个举例,假设数组为A[],总共有n个元素A1,A2....An。很显然,
当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A3~An],目标位target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题。

对于本题要求的求最接近解,只需要保存当前解以及当前解和目标的距离,如果新的解更接近,则更新解。算法复杂度为O(n^2);
注意:我们这里是求的和是一个非确定性的数,因此
2sum问题的hashtable解法就不适合这里了

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int n = num.size();
        sort(num.begin(),num.end());
        int res,dis=INT_MAX;
        for(int i = 0;i<n-2;i++)
        {
            int target2 = target - num[i];
            int tmpdis;
            int tmpres = twoSumClosest(num,i+1,target2);
            if((tmpdis = abs(tmpres-target2)) < dis)
            {
                res = tmpres + num[i];
                dis = tmpdis;
                if(res == target)
                    return res;
            }
        }
        return res;
    }
    
    int twoSumClosest(vector<int> &sortnum,int start,int target){
        int res,dis=INT_MAX;
        int l = start,r = sortnum.size()-1;
        while(l<r)
        {
            int sum = sortnum[l]+sortnum[r];
            if(sum < target)
            {
                if(target-sum < dis)
                {
                    res = sum;
                    dis = target - sum;
                }
                ++l;
            }
            else if(sum > target)
            {
                if(sum - target < dis)
                {
                    res = sum;
                    dis = sum - target;
                }
                --r;
            }
            else
                return target;
        }
        return res;
    }
};





 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { int no; char info; } VertexType; typedef struct { int edges[MAXV][MAXV]; int n, e; VertexType vexs[MAXV]; } MatGraph; void CreatMat(MatGraph &g, int A[MAXV][MAXV], int n, int e) { int i, j; g.n = n; g.e = e; for (i = 0; i < g.n; i++) for (j = 0; j < g.n; j++) g.edges[i][j] = A[i][j]; } void DispMat(MatGraph g) { int i, j; for (i = 0; i < g.n; i++) { for (j = 0; j < g.n; j++) if (g.edges[i][j] != INF) printf("%4d", g.edges[i][j]); else printf("%4s", "∞"); printf("\n"); } } int Prim(MatGraph g, int v) { int lowcost[MAXV], min, n = g.n, sum; int closest[MAXV], i, j, j; for (i = 0; i < n; i++) { lowcost[i] = g.edges[v][i]; closest[i] = v; } for (i = 1; i < n; i++) { min = INF; for (j = 0; j < n; j++) if (lowcost[j] != 0 && lowcost[j] < min) { min = lowcost[j]; k = j; } printf("\n 城市%d和城市%d之间的最短距离为:%d\n", closest[k] + 1, k + 1, min * 10); sum = sum + min; lowcost[k] = 0; for (j = 0; j < n; j++) if (g.edges[k][j] != 0 && g.edges[k][j] < lowcost[j]) { lowcost[j] = g.edges[k][j]; closest[j] = k; } } return sum; } int main() { int v = 3, k; MatGraph g; int A[MAXV][MAXV] = { {0, 6, 1, 5, INF, INF}, {6, 0, 5, INF, 3, INF}, {1, 5, 0, 5, 6, 4}, {5, INF, 5, 0, INF, 0, 6}, {INF, 3, 6, INF, 0, 6}, {INF, INF, 4, 2, 6, 0} }; int n = 6, e = 10; CreateMat(g, A, n, e); printf("城市连接图的邻接矩阵:\n"); DispMat(g); printf("\n普利姆算法求解结果:\n"); k = Prim(g, 0); printf("\n各个城市之间的总最短距离为:%d千米\n", k * 10); return 1; }改bug
06-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

godleft90

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值