C# solution: sort


  • 0
    B
    public class Solution 
    {
        public int FindUnsortedSubarray(int[] nums) 
        {
            if (nums.Length == 0) return 0;
    
            var sortedNums = new List<int>(nums);
            sortedNums.Sort();
    
            int left = -1;
            int right = -1;
            for(int i = 0; i < nums.Length; i++)
            {
                if (nums[i] != sortedNums[i])
                {
                    left = i;
                    break;
                }
            }
    
            for (int i = nums.Length - 1; i >= 0; i--)
            {
                if (nums[i] != sortedNums[i])
                {
                    right = i;
                    break;
                }
            }
    
            if (left == -1) return 0;
    
            return right - left + 1;
        }
    }
    

  • 1
    This post is deleted!

Log in to reply
 

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