Likou 581. The shortest unordered contiguous subarray

Question
Given an array of integers, you need to find a contiguous sub-array. If you sort this sub-array in ascending order, the entire array will become ascending.

The subarray you found should be the shortest, please output its length.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You only need to sort [6, 4, 8, 10, 9] in ascending order, then the entire table will be sorted in ascending order.
illustrate:

The length of the input array is in the range [1, 10,000].
The input array may contain duplicate elements, so ascending order means <=.
Solution 1:
Use sorting, then compare the sorted array with the one before sorting, and find the position where the first and last elements are different. The
code is as follows:

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left, right = 0, -1
        new_nums = sorted(nums)
        for i in range(len(nums)):
            if nums[i] != new_nums[i]:
                left = i 
                break
        for i in range(len(nums)):
            if nums[i] != new_nums[i]:
                right = i 
        return right - left + 1

Solution 2:
I learned a very good solution from the Internet, using double pointers;
(1) Left pointer processing, traverse the array in reverse, and find the position of the minimum value that is greater than the traversed part at the end, which is the element that needs to be changed initially
(2) Right pointer processing, traverse the array in the forward direction, and find the position of the maximum value that is smaller than the traversed part, that is, the position of the element that needs to be changed at the end. The
code is as follows:

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        left, right = 0, -1
        max, min = nums[0], nums[length - 1]
        for i in range(length):
            if nums[i] < max:
                right = i
            else: 
                max = nums[i]
            if nums[length - i - 1] > min:
                left = length - i - 1
            else:
                min = nums[length - i - 1]
        return right - left + 1

Time complexity: O(n)
Space complexity: O(1)
Ollie, this should be the optimal solution!

———————————————
Copyright statement: This article is an original article by the CSDN blogger "Houchang Village Village Chief", following the CC 4.0 BY-SA copyright agreement, please attach the original source for reprinting link and this statement.
Original link: https://blog.csdn.net/weixin_43927540/article/details/107639467

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339798&siteId=291194637