581. 最短无序连续子数组

给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

你找到的子数组应是最短的,请输出它的长度。

示例 1:

输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :

输入的数组长度范围在 [1, 10,000]。
输入的数组可能包含重复元素 ,所以升序的意思是<=。

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] tmp = (int[])Arrays.copyOf(nums, nums.length);
        Arrays.sort(tmp);
        boolean small = false, max = false;
        int count = nums.length, smallnum = 0, maxnum = 0;
        for(int i = 0; i < nums.length; i++)
        {
            if(!small)
            {
                if(i <= nums.length - 1 - maxnum)
                {
                    if(nums[i] == tmp[i])
                    {
                        smallnum++;
                        count--;
                    }
                    else
                        small = true;
                }
            }
            if(!max)
            {
                if(smallnum < nums.length - i - 1)
                {
                    if(nums[nums.length - i -1] == tmp[tmp.length - i -1])
                    {
                        count--;
                        maxnum++;
                    }
                    else
                        max = true;
                }
            }
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/Duancf/p/12633205.html