有一个二维数组,像 –
a[0] = [ 0 , 4 , 9 ]
a[1] = [ 2 , 6 , 11 ]
a[2] = [ 3 , 8 , 13 ]
a[3] = [ 7 , 12 ]
需要从每个子阵列中选择一个元素,使得最终数字的最大数与最小数之间的差最小.
上述的答案将是= [9,6,8,7].
做了一个算法,但不觉得它是一个好的.
在时间和空间复杂性方面做什么是有效的算法?
编辑 – 我的算法(在python) –
INPUT - Dictionary : table{}
OUTPUT - Dictionary : low_table{}
#
N = len(table)
for word_key in table:
for init in table[word_key]:
temp_table = copy.copy(table)
del temp_table[word_key]
per_init = copy.copy(init)
low_table[init]=[]
for ite in range(N-1):
min_val = 9999
for i in temp_table:
for nums in temp_table[i]:
if min_val > abs(init-nums):
min_val = abs(init-nums)
del_num = i
next_num = nums
low_table[per_init].append(next_num)
init = (init+next_num)/2
del temp_table[del_num]
lowest_val = 99
lowest_set = []
for x in low_table:
low_table[x].append(x)
low_table[x].sort()
mini = low_table[x][-1]-low_table[x][0]
if mini < lowest_val:
lowest_val = mini
lowest_set = low_table[x]
print lowest_set