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.
    
    
  • 相关阅读:
    Jdbc增删改查的相关操作(Oracle 数据库环境)
    java
    今日随笔
    爬虫之链家网
    爬虫之搜狗
    【题解】「UVA1149」装箱 Bin Packing
    【题解】「SP34013」SEUG
    【题解】「SP867」 CUBES
    【题解】NOI 系列题解总集
    APIO2019简要题解
  • 原文地址:https://www.cnblogs.com/tmortred/p/14488732.html
Copyright © 2011-2022 走看看