Shortest Unsorted Continuous Subarray
Description
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.Solution
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
if(n < 2) return 0;
int left = 1, right = 0;
int max_num = INT_MIN, min_num = INT_MAX;
for(int i = 0, j = n - 1; i < n; ++i, --j){
if(max_num > nums[i])
right = i;
else
max_num = nums[i];
if(min_num < nums[j])
left = j;
else
min_num = nums[j];
}
return right - left + 1;
}
};Last updated