LeetCode 题解工作台

最短无序连续子数组

给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。 请你找出符合题意的 最短 子数组,并输出它的长度。 示例 1: 输入: nums = [2,6,4,8,10,9,15] 输出: 5 解释: 你只需要对 [6, 4, 8, 10…

category

6

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 双·指针·invariant

bolt

答案摘要

我们可以先对数组进行排序,然后比较排序后的数组和原数组,找到最左边和最右边不相等的位置,它们之间的长度就是我们要找的最短无序连续子数组的长度。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 是数组的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

请你找出符合题意的 最短 子数组,并输出它的长度。

 

示例 1:

输入:nums = [2,6,4,8,10,9,15]
输出:5
解释:你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。

示例 2:

输入:nums = [1,2,3,4]
输出:0

示例 3:

输入:nums = [1]
输出:0

 

提示:

  • 1 <= nums.length <= 104
  • -105 <= nums[i] <= 105

 

进阶:你可以设计一个时间复杂度为 O(n) 的解决方案吗?

lightbulb

解题思路

方法一:排序

我们可以先对数组进行排序,然后比较排序后的数组和原数组,找到最左边和最右边不相等的位置,它们之间的长度就是我们要找的最短无序连续子数组的长度。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(n)O(n)。其中 nn 是数组的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        arr = sorted(nums)
        l, r = 0, len(nums) - 1
        while l <= r and nums[l] == arr[l]:
            l += 1
        while l <= r and nums[r] == arr[r]:
            r -= 1
        return r - l + 1
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate should efficiently identify the boundaries of the unsorted subarray using a two-pointer technique.

  • question_mark

    The interviewee should demonstrate how they maintain the invariant during the scanning process.

  • question_mark

    Look for a clear and optimal solution where the candidate explains the reasoning behind their approach.

warning

常见陷阱

外企场景
  • error

    Not updating the pointers correctly when scanning for the unsorted boundaries.

  • error

    Overlooking edge cases, like an already sorted array or a very short array.

  • error

    Confusing the invariant, leading to unnecessary subarray checks or inefficiencies.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to handle arrays that may contain duplicate elements.

  • arrow_right_alt

    Extend the problem by asking to sort the identified subarray and return the fully sorted array.

  • arrow_right_alt

    Introduce constraints on time complexity, such as requiring a solution that operates in O(n log n) or better.

help

常见问题

外企场景

最短无序连续子数组题解:双·指针·invariant | LeetCode #581 中等