C# Solution O(n) Time O(1) Space


  • 0
    U
    public class Solution {
        public int FindUnsortedSubarray(int[] nums) {
           // After start till end contains the unsorted continuous subarray. We need to Maintain that condition in the loop.
            if (nums == null || nums.Length <= 1) return 0;
            int i = 1;
            while (i < nums.Length && nums[i] >= nums[i-1]) i++;
            if (i >= nums.Length) return 0;
            
            int start = i-1; int end = start; int min = nums[start]; int max = nums[start];
            for (; i < nums.Length; i++){
                if (nums[i] >= max)max = nums[i];
                else if (nums[i] >= min) end = i;
                else {
                    while (start >= 0 && nums[i] < nums[start]) start--;
                    min = start >= 0 ? nums[start] : nums[i];
                    end = i;
                }
            }
            return end-start;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.