Leetcode: 581. Shortest Unsorted Continuous Subarray

description

Given an integer array nums, 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.
Return the shortest such subarray and output its length.

example

Input: nums = [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.

分析

用双头指针肯定会出错的,示例数据看上去很适合用双头指针

code

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        N = len(nums)
        p, q = 0, N-1
        cmin, cmax, premax = float('inf'), float('-inf'), float('-inf')
        for v in nums:
            if v >= premax:
                premax = v
                
                continue
            else:
                cmin = min(cmin, v)
                cmax = max(cmax, v, premax)
                
        if cmin == float('inf'):
            return 0
            
        for i in range(N):
            if nums[i] > cmin:
                p = i
                break
        
        for j in range(N-1, -1, -1):
            if cmax > nums[j]:
                q = j
                break
        return q - p + 1
        
O(n) 算法如下,就是用计算需要重新排序 segment 中最大值和最小值,用这个确定待重排 sub array 的坐标
Runtime: 168 ms, faster than 77.05% of Python online submissions for Shortest Unsorted Continuous Subarray.

原文地址:https://www.cnblogs.com/tmortred/p/14488732.html