#include <iostream>
int GetOrderLen(int arr[], int length)
{
if (length < 0)
return 0;
else if (length < 2)
return 1;
int maxLen = 0; // 记录最长有序子数组
int currentLen = 0; // 当前记录的有序数组长度
for (int i = 0; i < length - 1; i++)
{
if (arr[i] < arr[i + 1])
{
currentLen++;
}
else
{
if (currentLen > maxLen)
{
maxLen = currentLen;
}
currentLen = 0;
}
}
return maxLen;
}
int main()
{
// 测试用例1
const int length = 14;
int arr[length] = { 1, 7, 1, 2, 3, 5, 8, 11, 21, 31, 41, 1, 12, 6 };
std::cout << "maxLen: " << GetOrderLen(arr, length) << std::endl;
// 测试用例2
const int length1 = 31;
int arr1[length1] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 33, 1, 11, 7, 1, 2, 3, 5, 8, 11, 21, 31, 41, 1, 12, 6 };
std::cout << "maxLen: " << GetOrderLen(arr1, length1) << std::endl;
// 测试用例3
const int length2 = 1;
int arr2[length2] = {};
std::cout << "maxLen: " << GetOrderLen(arr2, length2) << std::endl;
}
计算复杂度为 O(n)。
张先超先生在书中给的伪代码计算复杂度是O(n2)。