581 Shortest Unsorted Continuous Subarray
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 <=.
The Idea: Find the first element iterating from the left that creates a conflict in creating an ascending array. Do the same thing iterating from the right. At this point, everything to the right of left
is sorted, and everything to the right of right
is sorted. The only thing left to do is to adapt our subarray between [left:right]
so that it create an entire sorted array. The way this is done is my moving the minimum element in [left:right]
to its rightful place on towards the left, and moving the maximum element in [left:right]
to its rightful place towards the right. As these elements get moved our left and right will expand.
Complexity: O(N) time and O(1) space
Last updated