JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given an integer array nums, 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.

Return the shortest such subarray and output its length.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

Code

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] sorted = new int[nums.length];

        for (int i = 0; i < nums.length; i++) {
            sorted[i] = nums[i];
        }

        Arrays.sort(sorted);

        int start = -1;
        int end = -1;
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != sorted[i] && start == -1) {
                start = i;
            } else if (nums[i] != sorted[i]) {
                end = i;
            }
        }

        return start == -1 ? 0 : end - start + 1;
    }
}
class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        Stack<Integer> incr = new Stack<>();
        Stack<Integer> decr = new Stack<>();
        int start = n;
        int end = -1; 

        for (int i = 0; i < n; i++) {
            // increase stack
            while (!incr.isEmpty() && nums[i] < nums[incr.peek()]) {
                start = Math.min(start, incr.pop());
            }

            incr.push(i);

            // decrease stack
            while (!decr.isEmpty() && nums[n - i - 1] > nums[decr.peek()]) {
                end = Math.max(end, decr.pop());
            }

            decr.push(n - i - 1);
        }

        if(end == -1) return 0;
        return end - start + 1;
    }
}
class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int len = nums.length;

        int end = -1;
        int max = nums[0];
        for (int i = 0; i < len; i++) {
            max = Math.max(max, nums[i]);

            if (max > nums[i]) {
                end = i;
            }
        }

        int start = len;
        int min = nums[len - 1];
        for (int i = len - 1; i >= 0; i--) {
            min = Math.min(min, nums[i]);

            if (min < nums[i]) {
                start = i;
            }
        }

        if(end == -1) return 0;

        return end - start + 1;
    }
}