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;
}

更多幹貨內容,歡迎關注我的公衆號:好奇碼農君
關注了之後就可以在手機上隨時隨地查看文章啦

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