LeetCode 题解工作台
全局倒置与局部倒置
给你一个长度为 n 的整数数组 nums ,表示由范围 [0, n - 1] 内所有整数组成的一个排列。 全局倒置 的数目等于满足下述条件不同下标对 (i, j) 的数目: 0 nums[i] > nums[j] 局部倒置 的数目等于满足下述条件的下标 i 的数目: 0 nums[i] > nums…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
根据题意,我们可以发现,一个数组中的局部倒置一定是全局倒置,但是全局倒置不一定是局部倒置。也就是说,全局倒置的数量一定大于等于局部倒置的数量。 因此,我们枚举每个数 ,其中 $2 \leq i \leq n - 1$,维护前缀数组 中的最大值,记为 。如果存在 大于 ,则说明全局倒置的数量大于局部倒置的数量,返回 `false` 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个长度为 n 的整数数组 nums ,表示由范围 [0, n - 1] 内所有整数组成的一个排列。
全局倒置 的数目等于满足下述条件不同下标对 (i, j) 的数目:
0 <= i < j < nnums[i] > nums[j]
局部倒置 的数目等于满足下述条件的下标 i 的数目:
0 <= i < n - 1nums[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.length1 <= n <= 1050 <= nums[i] < nnums中的所有整数 互不相同nums是范围[0, n - 1]内所有数字组成的一个排列
解题思路
方法一:维护前缀最大值
根据题意,我们可以发现,一个数组中的局部倒置一定是全局倒置,但是全局倒置不一定是局部倒置。也就是说,全局倒置的数量一定大于等于局部倒置的数量。
因此,我们枚举每个数 ,其中 ,维护前缀数组 中的最大值,记为 。如果存在 大于 ,则说明全局倒置的数量大于局部倒置的数量,返回 false 即可。
遍历结束后,返回 true。
时间复杂度 ,空间复杂度 。其中 为数组 nums 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.