LeetCode 题解工作台
半有序排列
给你一个下标从 0 开始、长度为 n 的整数排列 nums 。 如果排列的第一个数字等于 1 且最后一个数字等于 n ,则称其为 半有序排列 。你可以执行多次下述操作,直到将 nums 变成一个 半有序排列 : 选择 nums 中相邻的两个元素,然后交换它们。 返回使 nums 变成 半有序排列 所…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
我们可以先找到 和 的下标 和 ,然后根据 和 的相对位置,判断需要交换的次数。 如果 $i \lt j$,那么需要交换的次数为 $i + n - j - 1$;如果 $i \gt j$,那么需要交换的次数为 $i + n - j - 2$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你一个下标从 0 开始、长度为 n 的整数排列 nums 。
如果排列的第一个数字等于 1 且最后一个数字等于 n ,则称其为 半有序排列 。你可以执行多次下述操作,直到将 nums 变成一个 半有序排列 :
- 选择
nums中相邻的两个元素,然后交换它们。
返回使 nums 变成 半有序排列 所需的最小操作次数。
排列 是一个长度为 n 的整数序列,其中包含从 1 到 n 的每个数字恰好一次。
示例 1:
输入:nums = [2,1,4,3] 输出:2 解释:可以依次执行下述操作得到半有序排列: 1 - 交换下标 0 和下标 1 对应元素。排列变为 [1,2,4,3] 。 2 - 交换下标 2 和下标 3 对应元素。排列变为 [1,2,3,4] 。 可以证明,要让 nums 成为半有序排列,不存在执行操作少于 2 次的方案。
示例 2:
输入:nums = [2,4,1,3] 输出:3 解释: 可以依次执行下述操作得到半有序排列: 1 - 交换下标 1 和下标 2 对应元素。排列变为 [2,1,4,3] 。 2 - 交换下标 0 和下标 1 对应元素。排列变为 [1,2,4,3] 。 3 - 交换下标 2 和下标 3 对应元素。排列变为 [1,2,3,4] 。 可以证明,要让 nums 成为半有序排列,不存在执行操作少于 3 次的方案。
示例 3:
输入:nums = [1,3,4,2,5] 输出:0 解释:这个排列已经是一个半有序排列,无需执行任何操作。
提示:
2 <= nums.length == n <= 501 <= nums[i] <= 50nums是一个 排列
解题思路
方法一:寻找 1 和 n 的位置
我们可以先找到 和 的下标 和 ,然后根据 和 的相对位置,判断需要交换的次数。
如果 ,那么需要交换的次数为 ;如果 ,那么需要交换的次数为 。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def semiOrderedPermutation(self, nums: List[int]) -> int:
n = len(nums)
i = nums.index(1)
j = nums.index(n)
k = 1 if i < j else 2
return i + n - j - k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for how well the candidate identifies the positions of 1 and n.
- question_mark
Evaluate if the candidate optimizes the number of swaps needed for edge cases.
- question_mark
Check how the candidate handles scenarios where the permutation is already semi-ordered.
常见陷阱
外企场景- error
Candidates may not properly consider edge cases where the array is already semi-ordered.
- error
There might be confusion with how to calculate the number of swaps when 1 and n are close to each other.
- error
Not optimizing the number of operations in cases where no swaps are necessary.
进阶变体
外企场景- arrow_right_alt
What if the permutation is larger than 50 elements?
- arrow_right_alt
How would the problem change if the first and last elements were arbitrary numbers instead of 1 and n?
- arrow_right_alt
What if you were allowed to move elements around in groups rather than just swapping?