581. shortest unsorted continuous subarray

Given an integer array, 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, too.

You need to find the shortest such subarray and output its length.

Example 1:

1
2
3
Input: [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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class  {
public int findUnsortedSubarray(int[] nums) {
int[] arr = new int[nums.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = nums[i];
}
Arrays.sort(nums);
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] != arr[i]) {
break;
}
}
for (int j = nums.length - 1; j > i; j--) {
if (nums[j] != arr[j]) {
return j - i + 1;
}
}
return 0;
}
}