zoukankan      html  css  js  c++  java
  • 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.
    
    
  • 相关阅读:
    Java8 新特性(一)- Lambda 表达式
    省选知识复习
    [JSOI2016]灯塔/[POI2011]Lightning Conductor
    [十二省联考2019]春节十二响
    [tyvj1858]XLKxc
    [CF995F]Cowmpany Cowmpensation
    [集训队互测]calc
    拉格朗日插值法入门
    [TJOI2017]异或和
    [noi.ac省选模拟赛]第12场题解集合
  • 原文地址:https://www.cnblogs.com/tmortred/p/14488732.html
Copyright © 2011-2022 走看看