原題

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:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

Reference Answer

Method one

這個題竟然真的是排序之後,然後和原來的陣列進行比較得到的。

因為題目中的陣列的長度最大隻有1000,所以排序的時間不算很高。排序後的陣列和之前的陣列進行比較,找出最小的不相等的數字位置和最大不相等的數字的位置,兩者的差相減+1即為所求。

還能說什麼呢。。萬萬想不到。。

Code

class Solution:
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """     
        _len, _sorted = len(nums), sorted(nums)
        if nums == _sorted:
            return 0
        start_index  = min([index for index in range(_len) if nums[index] != _sorted[index]])
        end_index  = max([index for index in range(_len) if nums[index] != _sorted[index]])
        return end_index - start_index + 1 
        

C++ Version

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int length = nums.size();
        auto sorted_nums = nums;
        sort(sorted_nums.begin(), sorted_nums.end());
        int start_index = length, end_index = 0;
        for (int index = 0; index < length; ++index){
            if (nums[index] != sorted_nums[index]){
                start_index = min(start_index, index);
                end_index = max(end_index, index);
            }
            
        }
        return end_index >= start_index? end_index - start_index + 1: 0;
    }
};

Note

  • Python版的列表生成式很巧妙,要注意掌握!!
start_index  = min([index for index in range(_len) if nums[index] != _sorted[index]])
end_index  = max([index for index in range(_len) if nums[index] != _sorted[index]])
  • C++ 版的列表複製也要注意:auto sorted_nums = nums;以及排序演算法sort(sorted_nums.begin(), sorted_nums.end());

參考文獻

[1] https://blog.csdn.net/fuxuemingzhu/article/details/79254454