581. Shortest Unsorted Continuous Subarray

TAG: 数组

原题

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.

思路

这道题要求我们在一个数组里面找到最短的未排序的子数组,如果将这个子数组再排序一下,整个数组就成了排好的数组。

根据“将这个子数组排序一下,整个原数组就成了排好的数组”这一点,很容易想到,如果我们将整个数组先排序一遍,然后再和原来的数组放在一起比对,必然可以一眼看出哪些是排好的,哪些是需要重新排序的。

如下图所示


这样我们就很容易发现最左端和最右端的index了

那么代码如下:

public int findUnsortedSubarray(int[] nums) {
    int[] sorted = nums.clone();
    Arrays.sort(sorted);

    int start = nums.length;
    int end = 0;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != sorted[i]) {
            start = Math.min(start, i);
            end = Math.max(end, i);
        }
    }

    return end - start >= 0 ? end - start + 1 : 0;
}

更多干货内容,欢迎关注我的公众号:好奇码农君
关注了之后就可以在手机上随时随地查看文章啦

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章