leetcode 16 3Sum Closet

3Sum Closest
Total Accepted: 53147 Total Submissions: 195388 Difficulty: Medium

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

这道题的思路和之前的4Sum的思路一致,先把所有数增序排序,然后用三个指针,第一个指针从头到尾走形成第一层循环,第二个指针从第一个指针的下一个开始往后走,第三个指针从最后一个开始往前走,当第二个指针和第三个指针相遇时,就穷尽了在第一个指针固定的情况下,第二个数和第三个数的可能产生最接近值的组合情况,采用的策略是如果第二个数和第三个数相加的和大于target,则第三个指针往前走一个,因为之前已经按增序排序,所以第三个指针指向一个比之前小的值,如果第二个数和第三个数相加的和小于target,则第二个指针往后走一个,所以第二个指针指向一个比之前大的值。所以这个算法实际上是一个双重循环。

下面是完整程序代码:

#include <iostream>
#include <stdlib.h>
using namespace std;

int abs(int n)
{
    return n>0?n:-1*n;
}

int cmp(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}

int threeSumClosest(int* nums, int numsSize, int target) 
{
    qsort(nums, numsSize, sizeof(int), cmp);
    /*for(int i = 0; i < numsSize; i++)
    {
        cout<<nums[i]<<" ";
    }*/

    int optimal, difference = 10000000, p, q, tmp;


    for(int i = 0; i < numsSize - 2; i++)
    {
        p = i + 1;
        q = numsSize - 1;

        while(p < q)
        {
            tmp = nums[i] + nums[p] + nums[q] - target;
            if(abs(tmp) < difference)
            {
                difference = abs(tmp);
                optimal = nums[i] + nums[p] + nums[q];
            }

            if(tmp < 0)
                p++;
            else if(tmp == 0)
                return optimal;
            else
                q--;
        }
    }
    return optimal;
}

int main()
{
    int numsSize, *nums, target;
    cout<<"Input the size of numbers:"<<endl;
    cin>>numsSize;

    nums = (int*)malloc(sizeof(int) * numsSize);

    for(int i = 0; i < numsSize; i++)
    {
        cin>>nums[i];
    }

    cout<<"Input the target:"<<endl;
    cin>>target;

    cout<<endl<<threeSumClosest(nums, numsSize, target)<<endl; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值