Shortest Unsorted Continuous Subarray

 

CREATED TIME: Feb 03, 2020 8:37 PM UPDATED TIME: Feb 03, 2020 8:37 PM 난이도: Easy

class Solution { public: int findUnsortedSubarray(vector& nums) { vector c(nums.size()); copy(nums.begin(), nums.end(), c.begin()); int left = 1, right = -1; bool l_fixed = false; bool r_fixed = false;

        sort(c.begin(), c.end());
        
        for(int i=0; i<nums.size(); i++){
            if(nums[i] != c[i] && !l_fixed){
                left = i;
                l_fixed = true;
            }
            
            if(nums[nums.size() - 1 - i] != c[nums.size() - 1 - i] && !r_fixed){
                right = nums.size() - 1 - i;
                
                r_fixed = true;
            }
        }
        if (left > right){
            return 0;
        }else{
            return right - left + 1;
        }
    }
};