<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p>

<p>Return <em>the shortest such subarray and output its length</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,6,4,8,10,9,15]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1]
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>
<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> srtd;
        srtd = nums;
        // sort(srtd.begin(), srtd.end());

        // if(srtd == nums) return 0;

        int x=-1, y=-1;
        bool used =false;
        for(int i=1; i<nums.size(); i++){
            if(nums[i-1]>nums[i]) {
                x= i-1;
                break;
            }
        }

        for(int i=nums.size()-1; i>0; i--){
            if(nums[i-1]>nums[i]) {
                y= i;
                break;
            }
        }

        //already sorted
            if(x==-1 && y==-1){
                return 0;
            }
        //
        
        int mn = INT_MAX, mx = INT_MIN;

        for(int i=x; i<=y; i++){
            if(nums[i]<mn){
                mn = nums[i];
            }

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

        int resx=-1, resy=-1;
        for(int i=1; i<x; i++){
            if(mn<nums[i]) {resx = i-1; break;} 
        }

        for(int i=nums.size()-1; i>y; i--){
            if(mx>nums[i]) {resy = i+1; break;} 
        }

        x = upper_bound(nums.begin(), nums.begin() + x, mn) - nums.begin();
        y = lower_bound(nums.begin() + y + 1, nums.end(), mx) - nums.begin();
        return y - x;
    }
};
30400