按照提示写了暴力,过不了啊。。怎么看都是n ^3的时间复杂度,n=1000,照道理说time complexity = o(1000000000)也是过不了的。尝试这样理解吧,选定中间的数字,看左侧有多少小于(或大于)中间数字的元素(记为increas_left, decreas_left),同理看右侧有多少大于(或小于)中间数字的元素(记为increas_right, decreas_right)。则以此数为中间数的满足条件的combination的数量就是increas_left *increas_righ + decreas_left *decreas_right。这样可以降低复杂度到n^2.
class Solution:
def numTeams(self, rating: List[int]) -> int:
res = 0
for i in range(1, len(rating)-1):
increase_left = 0
increase_right = 0
decrease_left = 0
decrease_right = 0
for j in range(0, i):
if rating[j] < rating[i]:
increase_left += 1
elif rating[j] > rating[i]:
decrease_left += 1
for k in range(i+1, len(rating)):
if rating[i] < rating[k]:
increase_right += 1
elif rating[i] > rating[k]:
decrease_right += 1
res += increase_left*increase_right#increase triple
res += decrease_left*decrease_right#decrease triple
return res