算法——最短无序连续子数组

给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
链接: link.

解题思路:先对数组进行排序,然后用双指针,分别总头尾检索到第一个与原数组不相等的位置,两个指针之差就是答案。

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        if(n == 0 || n == 1) return 0;
        int[] temp = new int[n];
        for(int i = 0; i < n; i++) temp[i] = nums[i];
        Arrays.sort(temp);

        int i = 0, j = n - 1;
        while(i <= j &&nums[i] == temp[i]) i++;
        while(i <= j && nums[j] == temp[j]) j--;

        return j - i + 1;
    }
}
posted @ 2020-11-02 15:25  lippon  阅读(60)  评论(0编辑  收藏  举报