原题:
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)。先写一个快速排序算法,因此代码如下:
以上方法的主函数如下: