思路:遍历数组,如果当前元素等于给定元素,则开始寻找当前已排序子数组的长度,并更新最长已排序子数组的长度。
示例代码:
def longest_sorted_subarray(arr, x):
maxLength = 0
curLength = 0
preIndex = -1
start = -1
for i in range(len(arr)):
if arr[i] == x:
if preIndex == -1 or arr[preIndex] <= arr[i]:
curLength += 1
else:
curLength = 1
start = i
if curLength > maxLength:
maxLength = curLength
startIndex = start
else:
curLength = 0
preIndex = i
return arr[startIndex:(startIndex+maxLength)]
arr = [3, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3]
x = 5
print(longest_sorted_subarray(arr, x)) # [5, 6, 7, 8, 9]
上一篇:包含辅助方法 - 全局变量
下一篇:包含给定字母的单词