LeetCod : 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.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.

代码
直观感受,因为只有一个非序子数组,那么它一定在数组的中间。那么存在有序的只能在数组的两边。也就是我们需要找到非序子数组的最大值和最小值。左边有序部分需要小于最小值,右边有序部分需要大于最大值。
简单方法,排序数组然后比较:

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] snums = new int[nums.length];
        for(int i=0; i<nums.length; i++) snums[i] = nums[i];
        Arrays.sort(snums);
        
        int left = -1;
        while(left+1<nums.length && snums[left+1]==nums[left+1]) left++;
        left++;
        
        int right = nums.length;
        while(right-1>=0 && snums[right-1]==nums[right-1]) right--;
        right--;
        
        if(left>=right){
            return 0;
        }else{
            return right-left+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  l<r? r-l+1 : 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值