LeeCode581最短无序连续子数组(Java)(单调栈或简单排序)

题目链接:LeeCode581最短无序连续子数组
题目描述:在这里插入图片描述
拿到题秒出思路排序找对应位置不匹配的数组例:2,6,4,8,10,9,15
排序过后:2,4,6,8,9,10,15
不对应的位置就是4-9的长度得出5
代码:

class Solution {
    
    
    public static int findUnsortedSubarray(int[] nums) {
    
    
        if(nums.length==1||nums.length==0)return 0;
        int[] nums1 = nums.clone();
        int start=0,end=0;
        //排序
        Arrays.sort(nums1);
        //找第一个不匹配的位置
        for (int i = 0; i < nums.length; i++) {
    
    
            if(nums1[i]!=nums[i]){
    
    
                start=i;
                break;
            }
        }
        //从后往前找第一个不匹配的位置
        for (int i = nums.length-1; i >=0; i--) {
    
    
            if(nums1[i]!=nums[i]){
    
    
                end=i;
                break;
            }
        }
        
        if(end==0&&start==0)return 0;
        return end-start+1;
    }
}

过后看见了有进阶要求,看了题解才知道用单调栈,一个思路还是找出对应的位置

public class Solution {
    
    
    public int findUnsortedSubarray(int[] nums) {
    
    
        Stack < Integer > stack = new Stack < Integer > ();
        int l = nums.length, r = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            while (!stack.isEmpty() && nums[stack.peek()] > nums[i])
                l = Math.min(l, stack.pop());
            stack.push(i);
        }
        stack.clear();
        for (int i = nums.length - 1; i >= 0; i--) {
    
    
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i])
                r = Math.max(r, stack.pop());
            stack.push(i);
        }
        return r - l > 0 ? r - l + 1 : 0;
    }
}


猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/114580077