# 581. Shortest Unsorted Continuous Subarray

## 1. Question

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

## 2. Examples

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.


Example 2:

Input: nums = [1,2,3,4]
Output: 0


Example 3:

Input: nums = [1]
Output: 0


## 3. Constraints

1 <= nums.length <= 104 -105 <= nums[i] <= 105

## 5. Solutions

class Solution {
public int findUnsortedSubarray(int[] nums) {
if (null == nums || nums.length <= 1) {
return 0;
}

int cnt = 0;
int[] sorted = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sorted[i] = nums[i];
}
Arrays.sort(sorted);

ArrayList<Integer> integers = new ArrayList<>();

for (int i = 0; i < nums.length; i++) {
if (sorted[i] != nums[i]) {
}
}

Integer[] arr = integers.toArray(new Integer[0]);
Arrays.sort(arr);

if (0 == arr.length) {
return 0;
}

cnt = Math.max(arr[arr.length - 1] - arr[0] + 1, 0);

return cnt;
}
}