解题思路:
(1)假设目前已知[a1,a2,a3,...am,b1,b2,...bn],其中a表示无序排序的数组,b表示需要重新排序的数组
(2)假设接下来进入一个数,设为x,如果max[b1,b2,...bn]<x,那么重新排序的数组仍为[b1,b2,...bn]
(3)如果max[b1,b2,...bn]>=x,那么就需要判断x和[a1,a2,a3,...am]的关系。其中假设存在a1<=a2<=a3<=...<=x<=...<=am,并设此时x在其中的位置为i,那么新的需要重新排序的数组就为[ai,...am,b1,b2,...bn,x]
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int max = nums[0],count = 0;
vector<int > v;
vector<int>::iterator up;
v.push_back(max);
int i = 1;
while(i<nums.size() && max<= nums[i]) {
v.push_back(nums[i]);
max = nums[i];
i++;
}
v.pop_back();
i--;
int length = v.size();
while(i<nums.size()) {
if (max > nums[i]) {
up = upper_bound(v.begin(), v.begin()+length, nums[i]);
length = up-v.begin();
count = i - length + 1;
i++;
} else {
max = nums[i];
i++;
}
}
return count;
}
};