581. 最短无序连续子数组
# 581. 最短无序连续子数组 (opens new window)
# 1.双指针
分析:先通过两次遍历,找到头尾连续的最大不破坏递增序列的左右边界。左边界代表左边递增序列的最大值索引下标;右边界代表右边递增序列的最小值的索引下标。
接着修正左边界,如果当前节点比左边界的值要小,则左边界左移。右边界同理。
最终保证左边界的值一定是小于【left,right】范围内连续子数组最小值的最大值;有边界一定是大于连续子数组最大值的最小值。
class Solution {
public int findUnsortedSubarray(int[] nums) {
int start=0,end=nums.length-1;
for(;start+1<nums.length&&nums[start]<=nums[start+1];start++);
for(;end-1>=0&&nums[end]>=nums[end-1];end--);
for(int i=start+1;i<nums.length;i++){
while(start>=0&&nums[i]<nums[start])start--;
}
for(int i=end-1;i>=0;i--){
while(end<nums.length&&nums[i]>nums[end])end++;
}
if(start>=end) return 0;
return end-start-1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57