LeetCode 581. Shortest Unsorted Continuous Subarray (最短的未排序连续子阵列)

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dby_freedom https://blog.csdn.net/Dby_freedom/article/details/85101267

原题

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

没有更多推荐了,返回首页