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;
    }
}

 

posted @ 2019-04-16 11:05  起点菜鸟  阅读(240)  评论(0编辑  收藏  举报