用于最短无序子数组的 Python3 程序
给定一个长度为 n 的数组,问题是我们必须找到给定数组中最短的无序{既不增加也不减少}子数组的长度。
例子:
Input : n = 5
7 9 10 8 11
Output : 3
Explanation : 9 10 8 unordered sub array.
Input : n = 5
1 2 3 4 5
Output : 0
Explanation : Array is in increasing order.
这个想法是基于这样一个事实,即最短子数组的大小是 0 或 3。我们必须检查数组元素是增加还是减少,如果所有数组元素都在增加或减少,那么最短子数组的长度为 0,如果任一数组元素不跟随增加或减少,那么它的最短长度为 3。
Python3
# Python3 program to find shortest
# subarray which is unsorted
# Bool function for checking an array
# elements are in increasing
def increasing(a, n):
for i in range(0, n - 1):
if (a[i] >= a[i + 1]):
return False
return True
# Bool function for checking an array
# elements are in decreasing
def decreasing(a, n):
for i in range(0, n - 1):
if (a[i] < a[i + 1]):
return False
return True
def shortestUnsorted(a, n):
# increasing and decreasing are two functions.
# if function return True value then print
# 0 otherwise 3.
if (increasing(a, n) == True or
decreasing(a, n) == True):
return 0
else:
return 3
# Driver code
ar = [7, 9, 10, 8, 11]
n = len(ar)
print(shortestUnsorted(ar, n))
# This code is contributed by Smitha Dinesh Semwal.
输出 :
3
有关更多详细信息,请参阅有关最短无序子阵列的完整文章!