public class Solution { public int FindUnsortedSubarray(int[] nums) { int n = nums.Length, beg = -1, end = -2, min = nums[n - 1], max = nums[0]; for (int i = 1; i < n; i++) { max = Math.Max(max, nums[i]); min = Math.Min(min, nums[n - 1 - i]); if (nums[i] < max) { end = i; } if (nums[n - 1 - i] > min) { beg = n - 1 - i; } } return end - beg + 1; } }
https://leetcode.com/problems/shortest-unsorted-continuous-subarray/#/description
另外一种比较容易理解的方案:
public class Solution { public int FindUnsortedSubarray(int[] nums) { int n = nums.Length; var temp = new List<int>(); for (int i = 0; i < n; i++) { temp.Add(nums[i]); } temp = temp.OrderBy(x => x).ToList(); int start = 0; while (start < n && nums[start] == temp[start]) { start++; } //正序找到第一个不同,确定start的位置 int end = n - 1; while (end > start && nums[end] == temp[end]) { end--; } //逆序找到第一个不同,确定end的位置 return end - start + 1; } }
补充一个python的实现:
1 class Solution: 2 def findUnsortedSubarray(self, nums: 'List[int]') -> int: 3 n = len(nums) 4 temp = sorted(nums) 5 start,end = 0,n-1 6 while start < n and temp[start] == nums[start]: 7 start += 1 8 while end > start and temp[end] == nums[end]: 9 end -= 1 10 return end - start + 1