https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
int findUnsortedSubarray(vector<int>& nums) {
nums.insert(nums.begin(), INT_MIN);
nums.push_back(INT_MAX);
int l = 0, h = nums.size() - 1;
for(int i=1; i<nums.size()-1; i++ ) {
if(nums[i]<nums[l]) {
while(nums[i]<nums[l]) l--;
}
else if(l == i-1) l++;
}
for(int i=nums.size()-2; i>=0; i-- ) {
if(nums[i]>nums[h]) {
while(nums[i]>nums[h]) h++;
}
else if(h == i+1) h--;
}
return max(h-l-1, 0);
}
No comments:
Post a Comment