Python 将最大元素为k的子阵列计数
给定一个数组和一个数字k,您需要计算其中k为最大值的子数组的数量 例如,在数组[4,1,2,3,1,5]中,k=3。所以这个数组的计数是6 我提出了以下解决方案:Python 将最大元素为k的子阵列计数,python,optimization,Python,Optimization,给定一个数组和一个数字k,您需要计算其中k为最大值的子数组的数量 例如,在数组[4,1,2,3,1,5]中,k=3。所以这个数组的计数是6 我提出了以下解决方案: count = 0 n = len(a) for i in range(n): for j in range(i,n): b = a[i:j] if k in b and max(b) == k: count += 1 return count 其时间复杂度为O(n^2)。如何对其进行优化(最好使用
count = 0
n = len(a)
for i in range(n):
for j in range(i,n):
b = a[i:j]
if k in b and max(b) == k:
count += 1
return count
其时间复杂度为O(n^2)。如何对其进行优化(最好使用双指针方法)以获得O(n)解决方案?列表中唯一
k
的一个解决方案:
k = 3
a = [4,1,2,3,1,5]
length = len(a)
ucount, lcount = 0, 0
# Find the index of k:
index = a.index(k)
# From this position, go in one direction until a larger number is found
# increment ucount for each step
upper = index
while upper < length and a[upper] <= k:
ucount += 1
upper += 1
# After that, go from index backwards until a larger number is found
# increment lcount for each step
lower = index
while lower >= 0 and a[lower] <= k:
lcount += 1
lower -= 1
# Multiply the upper and lower count
print(ucount*lcount)
k=3
a=[4,1,2,3,1,5]
长度=长度(a)
ucount,lcount=0,0
#查找k的索引:
索引=a.索引(k)
#从这个位置开始,朝一个方向走,直到找到一个更大的数字
#每个步骤的增量ucount
上限=索引
当upperk
唯一的时,或者该数字可以出现多次?我目前正在寻找k唯一的解决方案。但我希望有一个解决方案,当k出现不止一次时也能起作用