想法是將數組複製一下,將複製後的數組進行排序。創建兩個指針,從兩頭對比兩個數組,直到找到不相等的位置。然後就得出了結果。
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;
}
}