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.
    
    
  • 相关阅读:
    2021/9/20 开始排序算法
    快速排序(自己版本)
    2021/9/17(栈实现+中后缀表达式求值)
    2021/9/18+19(中缀转后缀 + 递归 迷宫 + 八皇后)
    20212021/9/13 稀疏数组
    2021/9/12 线性表之ArrayList
    开发环境重整
    Nginx入门
    《财富的帝国》读书笔记
    Linux入门
  • 原文地址:https://www.cnblogs.com/tmortred/p/14488732.html
Copyright © 2011-2022 走看看