581. 最短无序连续子数组
给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
请你找出符合题意的 最短 子数组,并输出它的长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int findUnsortedSubarray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = nums.length - 1;
int right = 0;
int leftMax = nums[0];
for (int i = 0; i < nums.length; ++i) {
if (nums[i] < leftMax) {
right = i;
}
leftMax = Math.max(leftMax, nums[i]);
}
int rightMin = nums[nums.length - 1];
for (int i = nums.length - 1; i >= 0; --i) {
if (nums[i] > rightMin) {
left = i;
}
rightMin = Math.min(rightMin, nums[i]);
}
return right > left ? right - left + 1 : 0;
}
}