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.

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:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

Source-Time-O(1)-Space)

This solution is using O(n) time, it finds the begining and end of the array from both ends.
If end < beg < 0 at the end of the for loop, then the array is already fully sorted.

The end = -2 is smart, you can always return end - beg + 1, no need to check if the array is already sorted.

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n=nums.length, max = 0, min=nums.length-1, start=-1, end=-2;
        for(int i=0;i<nums.length;i++){
            if(nums[i]<nums[max])   end=i;
            else if(nums[i]>nums[max]) max=i;

            if(nums[n-1-i]>nums[min]) start=n-1-i;
            else if(nums[n-1-i]<nums[min]) min=n-1-i;
        }

        return end-start+1;
    }
}