mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 02:53:42 +00:00
Update 51. 数组中的逆序对.md
补充归并排序统计逆序对的原理与示例分析,补充合并统计过程示意图。
This commit is contained in:
@@ -8,6 +8,14 @@
|
||||
|
||||
## 解题思路
|
||||
|
||||
暴力枚举所有数对需要 O(N<sup>2</sup>)。归并排序在合并两个有序的子数组时,可以一次统计出一批逆序对:左半边 nums[l..m] 和右半边 nums[m+1..h] 都已有序,当 nums[i] > nums[j] 时,左半边从 i 到 m 的元素都不小于 nums[i],也就都大于 nums[j],一次就能加上 m - i + 1 个逆序对。两半内部的逆序对在递归时已经统计过,合并时只统计跨两半的,总的时间复杂度为 O(NlogN)。
|
||||
|
||||
以 [9, 7, 5, 4, 6] 为例,左半边 [9, 7, 5] 内部有 3 个逆序对,排序后为 [5, 7, 9];右半边 [4, 6] 内部没有。最后一次合并统计跨两半的 5 个,共 8 个:
|
||||
|
||||
<div align="center"> <img src="pics/offer51-merge-count.png" width="620px"/> </div><br>
|
||||
|
||||
需要注意的是两边相等时先取左边的元素,相等的两个数不是逆序对。
|
||||
|
||||
```java
|
||||
private int cnt = 0;
|
||||
private int[] tmp;
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 111 KiB |
Reference in New Issue
Block a user