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; } }