LeetCode 题解工作台
翻转对
给定一个数组 nums ,如果 i 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个 重要翻转对 。 你需要返回给定数组中的重要翻转对的数量。 示例 1: 输入 : [1,3,2,3,1] 输出 : 2 示例 2: 输入 : [2,4,3,5,1] 输出 : 3 注意: …
7
题型
4
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
归并排序的过程中,如果左边的数大于右边的数,则右边的数与左边的数之后的数都构成逆序对。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为数组长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给定一个数组 nums ,如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对。
你需要返回给定数组中的重要翻转对的数量。
示例 1:
输入: [1,3,2,3,1] 输出: 2
示例 2:
输入: [2,4,3,5,1] 输出: 3
注意:
- 给定数组的长度不会超过
50000。 - 输入数组中的所有数字都在32位整数的表示范围内。
解题思路
方法一:归并排序
归并排序的过程中,如果左边的数大于右边的数,则右边的数与左边的数之后的数都构成逆序对。
时间复杂度 ,空间复杂度 。其中 为数组长度。
class Solution:
def reversePairs(self, nums: List[int]) -> int:
def merge_sort(l, r):
if l >= r:
return 0
mid = (l + r) >> 1
ans = merge_sort(l, mid) + merge_sort(mid + 1, r)
t = []
i, j = l, mid + 1
while i <= mid and j <= r:
if nums[i] <= 2 * nums[j]:
i += 1
else:
ans += mid - i + 1
j += 1
i, j = l, mid + 1
while i <= mid and j <= r:
if nums[i] <= nums[j]:
t.append(nums[i])
i += 1
else:
t.append(nums[j])
j += 1
t.extend(nums[i : mid + 1])
t.extend(nums[j : r + 1])
nums[l : r + 1] = t
return ans
return merge_sort(0, len(nums) - 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Assess the candidate's ability to optimize brute force solutions using merge sort or binary search techniques.
- question_mark
Look for familiarity with binary indexed trees or segment trees for optimizing the solution's space and time complexity.
- question_mark
Evaluate how well the candidate applies divide and conquer strategies to complex counting problems.
常见陷阱
外企场景- error
Overlooking optimization opportunities and resorting to brute force, which is inefficient for larger inputs.
- error
Failure to correctly handle edge cases, such as arrays with very small or very large numbers.
- error
Misunderstanding the problem statement and incorrectly counting pairs that do not satisfy the reverse pair condition.
进阶变体
外企场景- arrow_right_alt
What if the array contains negative numbers or zeros? Ensure the solution handles such edge cases properly.
- arrow_right_alt
What if the array length exceeds typical constraints? Test the solution’s efficiency for large arrays (up to 5 * 10^4).
- arrow_right_alt
How would you approach solving this problem if the input array was sorted? Consider variations where sorting the array first can help with optimizations.