想法是将数组复制一下,将复制后的数组进行排序。创建两个指针,从两头对比两个数组,直到找到不相等的位置。然后就得出了结果。
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int[] copy = Arrays.copyOf(nums, nums.length);
Arrays.sort(copy);
int i = 0;
int j = nums.length - 1;
while (i < nums.length && copy[i] == nums[i]) {
i++;
}
while (i < j && copy[j] == nums[j]) {
j--;
}
if (i < j)
return j - i + 1;
else return 0;
}
}