N个数中找三个数,使其和的绝对值最小--

原题:

        Write a function to find any subset of 3 integers from a set of N integers that have a sum with the smallest absolute value, and analyze the time and space complexity of your function.

The input to this function is a pointer or reference to an array of integers, along with the value of N.
When
N >= 3, the output is a 3-element array of integers, such that their sum has the smallest absolute value.

When
N < 3, the output is null.


For example, given the following input:

{-99, -66, 0, 2, 3}, your function should return {0, 2, 3}.

 

题意即:

       给定包含N个数的无序数组S(可能包含负数,0,正数)。求三个数A,B,C,使其和的绝对值最小。
       例如:S={-9,0,1,3,6},A=-9,B=3,C=6,MIN=0

 

 

==================================================================

 

 

法一、暴力搜索法,三重循环枚举3个数,时间复杂度为O(N^3),代码如下:

 

 

 

法二、对数组a排序后枚举其中2个数,二分查找另一个数。O(N^2*LOGN)

 

 

法三、对数组a排序后枚举其中1个数cur(a[i]),使用双向指针head、tail从数组两端更新(注意剔除掉cur)。根据a[head]+a[tail]+cur的正负号来更新head或tail。若为负则head++,否则tail--。一旦和为0即退出。同时根据此和来更新MIN。最后MIN即为所求。利用三个变量X,Y,Z记录任一最优解在排序后数组中的下标。该方法最坏的时间复杂度为O(N^2)。先写一个快速排序算法,因此代码如下:

 

 

 

 

 

 

以上方法的主函数如下:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值