https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/solution/zui-duan-wu-xu-lian-xu-zi-shu-zu-by-leet-yhlf/

法一:排序

来源:力扣
image.png

  1. // 法一: 排序
  2. public int findUnsortedSubarray(int[] nums) {
  3. int[] numsSorted = new int[nums.length];
  4. System.arraycopy(nums, 0, numsSorted, 0, nums.length);
  5. Arrays.sort(numsSorted);
  6. int left = 0;
  7. int right = nums.length - 1;
  8. while (nums[left] == numsSorted[left]) {
  9. left++;
  10. // 要是数组本来就是全部有序的,那么就会有这种情况
  11. if (left > right) {
  12. return 0;
  13. }
  14. }
  15. while (nums[right] == numsSorted[right]) {
  16. right--;
  17. }
  18. return right - left + 1;
  19. }