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:
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.
解法
时间复杂度O(n),空间复杂度O(1).从左往右遍历,如果比最大的值小则存在逆序;从右往左遍历,如果比最小的值大则存在逆序。记录两个逆序点相减+1.
public class Solution {
public int findUnsortedSubarray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int len = nums.length;
int left = 0;
int right = 0;
for (int i = 0; i < len; i++) {
if (nums[i] < max) {
right = i;
}
max = Math.max(max, nums[i]);
}
for (int j = len - 1; j >= 0; j--) {
if (nums[j] > min) {
left = j;
}
min = Math.min(min, nums[j]);
}
return left == right ? 0 : right - left + 1;
}
}