我最近试图解决在俄亥俄的一些任务,我发现,解决办法似乎很复杂:O(nlog n),但我认为,某些投入(例如第1参数为0
和pairs
,是很长的零件清单)。
它还有三个层次的<条码>。 我认为,它可以优化,但此时我无法优化它,我可能只是缺少一些显而易见的事情。
因此,问题基本上如下:
鉴于分类账清单(
Values
),该功能必须退还符合以下标准的指数奶制品数量:
- lets assume single index pair is a tuple like
(index1, index2)
,- then
values[index1] == complementary_diff - values[index2]
is true,Example: If given a list like
[1, 3, -4, 0, -3, 5]
asvalues
and1
ascomplementary_diff
, the function should return4
(which is the length of the following list of indexes pairs:[(0, 3), (2, 5), (3, 0), (5, 2)]
).
这正是我迄今为止所做的,它应当尽最大努力,但正如我所说的那样,在某些情况下,尽管其复杂性已接近O(nlog n),它仍然能够运行非常缓慢。 (如悲观复杂度为O(n^2))。
def complementary_pairs_number (complementary_diff, values):
value_key = {} # dictionary storing indexes indexed by values
for index, item in enumerate(values):
try:
value_key[item].append(index)
except (KeyError,): # the item has not been found in value_key s keys
value_key[item] = [index]
key_pairs = set() # key pairs are unique by nature
for pos_value in value_key: # iterate through keys of value_key dictionary
sym_value = complementary_diff - pos_value
if sym_value in value_key: # checks if the symmetric value has been found
for i1 in value_key[pos_value]: # iterate through pos_values indexes
for i2 in value_key[sym_value]: # as above, through sym_values
# add indexes pairs or ignore if already added to the set
key_pairs.add((i1, i2))
key_pairs.add((i2, i1))
return len(key_pairs)
For the given example it behaves like that:
>>> complementary_pairs_number(1, [1, 3, -4, 0, -3, 5])
4
如果看看该法典如何“被保留”或“简化”,请让我知道。
我不敢肯定,如果你认为是最佳办法,请让我知道。
EDIT: I have corrected the example (thanks, unutbu!).