LeetCode 题解工作台

全局倒置与局部倒置

给你一个长度为 n 的整数数组 nums ,表示由范围 [0, n - 1] 内所有整数组成的一个排列。 全局倒置 的数目等于满足下述条件不同下标对 (i, j) 的数目: 0 nums[i] > nums[j] 局部倒置 的数目等于满足下述条件的下标 i 的数目: 0 nums[i] > nums…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

根据题意,我们可以发现,一个数组中的局部倒置一定是全局倒置,但是全局倒置不一定是局部倒置。也就是说,全局倒置的数量一定大于等于局部倒置的数量。 因此,我们枚举每个数 ,其中 $2 \leq i \leq n - 1$,维护前缀数组 中的最大值,记为 。如果存在 大于 ,则说明全局倒置的数量大于局部倒置的数量,返回 `false` 即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 的整数数组 nums ,表示由范围 [0, n - 1] 内所有整数组成的一个排列。

全局倒置 的数目等于满足下述条件不同下标对 (i, j) 的数目:

  • 0 <= i < j < n
  • nums[i] > nums[j]

局部倒置 的数目等于满足下述条件的下标 i 的数目:

  • 0 <= i < n - 1
  • nums[i] > nums[i + 1]

当数组 nums全局倒置 的数量等于 局部倒置 的数量时,返回 true ;否则,返回 false

 

示例 1:

输入:nums = [1,0,2]
输出:true
解释:有 1 个全局倒置,和 1 个局部倒置。

示例 2:

输入:nums = [1,2,0]
输出:false
解释:有 2 个全局倒置,和 1 个局部倒置。
 

提示:

  • n == nums.length
  • 1 <= n <= 105
  • 0 <= nums[i] < n
  • nums 中的所有整数 互不相同
  • nums 是范围 [0, n - 1] 内所有数字组成的一个排列
lightbulb

解题思路

方法一:维护前缀最大值

根据题意,我们可以发现,一个数组中的局部倒置一定是全局倒置,但是全局倒置不一定是局部倒置。也就是说,全局倒置的数量一定大于等于局部倒置的数量。

因此,我们枚举每个数 nums[i]nums[i],其中 2in12 \leq i \leq n - 1,维护前缀数组 nums[0,..i2]nums[0,..i-2] 中的最大值,记为 mxmx。如果存在 mxmx 大于 nums[i]nums[i],则说明全局倒置的数量大于局部倒置的数量,返回 false 即可。

遍历结束后,返回 true

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为数组 nums 的长度。

1
2
3
4
5
6
7
8
class Solution:
    def isIdealPermutation(self, nums: List[int]) -> bool:
        mx = 0
        for i in range(2, len(nums)):
            if (mx := max(mx, nums[i - 2])) > nums[i]:
                return False
        return True
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Checks if you understand the distinction between local and global inversions.

  • question_mark

    Wants you to optimize beyond brute-force nested loops.

  • question_mark

    Seeks recognition of permutation constraints and mathematical bounds for array positions.

warning

常见陷阱

外企场景
  • error

    Counting inversions directly with nested loops causes timeouts for large arrays.

  • error

    Ignoring that local inversions are always global inversions can lead to false negatives.

  • error

    Not considering positions two or more apart for global inversions results in incorrect answers.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine the number of global inversions minus local inversions instead of boolean check.

  • arrow_right_alt

    Handle arrays that are not strict permutations, requiring extra validation.

  • arrow_right_alt

    Extend to k-local inversions, where an inversion spans at most k indices.

help

常见问题

外企场景

全局倒置与局部倒置题解:数组·数学 | LeetCode #775 中等