Leetcode 581. Shortest Unsorted Continuous Subarray
Given an integer array nums
, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return the length of the shortest such subarray.
nums = [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9]
to make the whole array sorted in ascending order.nums = [1, 2, 3, 4]
Output: 0
Explanation: The array is already sorted.nums = [1]
Output: 0
Explanation: The array is already sorted.0
as there’s nothing to sort.1 <= nums.length <= 10^4
and -10^5 <= nums[i] <= 10^5
can be assumed.O(n)
where n
is the length of the array.0
. Otherwise, return the length between the identified boundaries.#include <vector>
#include <algorithm>
#include <limits.h>
class Solution {
public:
int findUnsortedSubarray(std::vector<int>& nums) {
int n = nums.size();
int start = -1, end = -1;
// Traverse from beginning to find the first out of order element.
for (int i = 1; i < n; ++i) {
if (nums[i] < nums[i - 1]) {
start = i - 1;
break;
}
}
// Traverse from end to find the first out of order element.
for (int i = n - 1; i > 0; --i) {
if (nums[i] < nums[i - 1]) {
end = i;
break;
}
}
// If already sorted
if (start == -1 && end == -1) return 0;
// Find min and max in the unsorted subarray
int subarray_min = INT_MAX, subarray_max = INT_MIN;
for (int i = start; i <= end; ++i) {
if (nums[i] < subarray_min) subarray_min = nums[i];
if (nums[i] > subarray_max) subarray_max = nums[i];
}
// Extend the start to the left
while (start > 0 && nums[start - 1] > subarray_min) --start;
// Extend the end to the right
while (end < n - 1 && nums[end + 1] < subarray_max) ++end;
return end - start + 1;
}
};
O(n)
as it involves a few linear scans of the array. The space complexity is O(1)
as no additional space proportional to the input size is used.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?