Shortest Unsorted Continuous Subarray
Description
Given an integer array, 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, too.
You need to find the shortest such subarray and output its length.
Example 1:
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
Solution
Idea:
Find longest subarray
nums[0..right]
such thatmax(nums[0..right]) <= nums[right+1..n-1]
.Find longest subarray
nums[left..n-1]
such thatmin(nums[left..n-1]) >= nums[0..left-1]
.The shortest subarray we want to find is
nums[left..right]
. We can prove it by contradiction.
Last updated