给定一个大小为N的整数数组,如何有效地找到大小为K且元素彼此最接近的子集?
让子集 (x1,x2,x3,..xk) 的接近度定义为:
2 <= N <= 10^5
2 <= K <= N
约束:数组可能包含重复项,不保证已排序。
对于大 N,我的蛮力解决方案非常慢,并且它不检查是否有超过 1 个解决方案:
N = input()
K = input()
assert 2 <= N <= 10**5
assert 2 <= K <= N
a = []
for i in xrange(0, N):
a.append(input())
a.sort()
minimum = sys.maxint
startindex = 0
for i in xrange(0,N-K+1):
last = i + K
tmp = 0
for j in xrange(i, last):
for l in xrange(j+1, last):
tmp += abs(a[j]-a[l])
if(tmp > minimum):
break
if(tmp < minimum):
minimum = tmp
startindex = i #end index = startindex + K?
例子:
N = 7
K = 3
array = [10,100,300,200,1000,20,30]
result = [10,20,30]
N = 10
K = 4
array = [1,2,3,4,10,20,30,40,100,200]
result = [1,2,3,4]