Get min Len of unsorted arr's subarr
需要排序的最短子数组长度
给定一个无序数组,求出需要返回的最短子数组的长度
arr = [1, 5, 3, 4, 6, 7] [5, 3, 4, 2]
#include <vector>
#include <iostream>
using namespace std;
int getMinLen(vector<int> &arr){
int n = arr.size();
if(n <= 0) return 0;
int minNum = arr[n - 1];
int minIndex = -1;
for(int i = n - 2; i >= 0; i--){
if(arr[i] > minNum){
minIndex = i;
}else{
minNum = min(minNum, arr[i]);
}
}
if(minIndex == -1) return 0;
int maxNum = arr[0];
int maxIndex = -1;
for(int i = 1; i <= n-1; i++){
if(arr[i] < maxNum){
maxIndex = i;
}else{
maxNum = max(maxNum, arr[i]);
}
}
return maxIndex - minIndex + 1;
}
int main(){
vector<int> test ={1 ,5, 3, 4, 2, 8, 7};
cout<<getMinLen(test)<<endl;
return 0;
}