leetcode[Shortest Unsorted Continuous Subarray]//待整理多种解法

来源:互联网 发布:查看占用80端口的进程 编辑:程序博客网 时间:2024/06/05 04:52

解法一:

class Solution {    public int findUnsortedSubarray(int[] nums) {        //既然要找出最短的需要排序的子序列,从而让整个数组处于升序的状态    //那么就将数组排序后,两个数组从收尾进行对比,找出最开始不一致的(这是合理的,因为要求把子序列排序后,就处于升序,所以不存在找出多个子序列来比较长度的情况)        int[] copy = nums.clone();//得出一个原数组的备份,因为调用Arrays.sort()会将原数组改变    Arrays.sort(copy);    int head = 0;    while(head < nums.length){    if(nums[head] != copy[head])    break;    head++;    }        int tail = nums.length - 1;    while(tail >= 0){    if(nums[tail] != copy[tail])    break;    tail--;    }        if(head > tail){//说明没有需要重排的    return 0;    } else{    return tail - head + 1;    }    }}


阅读全文
1 0
原创粉丝点击