• 581. Shortest Unsorted Continuous Subarray


    Given an integer array, 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, too.

    You need to find the shortest such subarray and output its length.

    给你一个数组,找一个最短的连续子数组,对这个子数组排序,整个数组就升序

    需要从做到右找到第一个大于后面数字的下标l,从右到左找到第一个小于前面数字的下标r

    然后再nums[l : r + 1]找到最大值和最小值,然后左边从l往左找到不大于min的l,右边从r往右找到不小于max的r,答案就是r - l + 1

    这题标成easy不太合适吧

    class Solution(object):
        def findUnsortedSubarray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            if n < 2:
                return 0
            l = 0
            r = n - 1
            while l + 1 < n and nums[l + 1] >= nums[l]:
                l += 1
            while r >= 1 and nums[r - 1] <= nums[r]:
                r -= 1
            if l > r:
                return 0
            max_v = max(nums[l: r + 1])
            min_v = min(nums[l: r + 1])
            while l >= 1 and nums[l - 1] > min_v:
                l -= 1
            while r + 1 < n and nums[r + 1] < max_v:
                r += 1
            return r - l + 1
  • 相关阅读:
    存储型 XSS 原理复现
    反射型 XSS 原理复现
    HTTP 简易理解
    Markdown 流程图语法
    Dirsearch 快速开始
    sqlmap 快速开始
    SQL 注入原理
    XSS 原理
    51nod 1835 完全图
    11.5 AM 请求
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13308591.html
Copyright © 2020-2023  润新知