解题思路就是创建一个临时数组用来保存已有数据,然后对临时数组进行排序,再对临时数组与原数组进行对比,从前往后找出第一个不同的索引值,从后往前找出第一个不同的值,相减加1就可以得到目标值。

public class Solution {

public int findUnsortedSubarray (int[] nums) {
    // write code here
    if(nums==null||nums.length==0){
        return 0;
    }
    int length = nums.length;
    int[] temp = new int[length];
    System.arraycopy(nums,0,temp,0,length);
    //排序
    Arrays.sort(temp);
    //如果原数组就是排好序的直接返回0
    int index = 0;
    for (int i = 0; i < nums.length; i++) {
        if(temp[i]!=nums[i]){
            index=i;
            break;
        }else {
            index=i;
        }
    }
    if(index==length-1){
        return 0;
    }
    //从前往后找,找出第一个不同值对应的索引值
    int left = 0;
    int right = length-1;
    for (int i = 0; i < nums.length; i++) {
        if(temp[i]!=nums[i]){
            left=i;
            break;
        }else {
            left=i;
        }
    }
    //从后往前找,找出第一个不同值对应的索引值
    for (int i = nums.length - 1; i >= 0; i--) {
        if(temp[i]!=nums[i]){
            right=i;
            break;
        }
    }
    return right-left+1;
}

}