LeetCode 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.

题解:

这个题虽然是easy,但是是leetcode上标记为Google 的面试题。

解法一:预先排序,找到最左边和最右边与排序后的数组不一样的地方

T:O(nlogn)

S:  O(n)

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] sorted = nums.clone();
        Arrays.sort(sorted);
        int start = 0;
        while(start < nums.length) {
            if(nums[start] != sorted[start]) {
                break;
            }
            start++;
        }
        int end = nums.length - 1;
        while(end > start) {
            if(nums[end] != sorted[end]) {
                break;
            }
            end--;
        }
        return end - start + 1;
    }
}

解法二:递减栈,递增栈

T: O(n)

S: O(n)

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        int r = 0, l = nums.length - 1;
        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;
    }
}

解法三: 没有额外空间的O(n)时间复杂度

参看链接:https://www.cnblogs.com/jimmycheng/p/7673733.html

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        int beg = -1;
        int end = -2;
        for(int i = 0; i < nums.length; i++) {
            max = Math.max(nums[i], max);
            min = Math.min(nums[nums.length - 1 - i], min);
            
            if(max > nums[i]) {
                end = i;
            }
            if(min < nums[nums.length - 1 - i]) {
                beg = nums.length - 1 - i;
            }
        }
        System.out.println(beg + " " + end);
        return end - beg + 1;
    }
}

 

转载于:https://www.cnblogs.com/rookielet/p/10715680.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值