【題目描述】
For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.
在數組中的兩個數字如果前面一個數字大于后面的數字,則這兩個數字組成一個逆序對。給你一個數組,求出這個數組中逆序對的總數。
概括:如果a[i] > a[j] 且 i < j, a[i] 和 a[j] 構成一個逆序對。
【題目鏈接】
www.lintcode.com/en/problem/reverse-pairs/
【題目解析】
可以利用樹狀數組 (Binary Indexed Tree / Fenwick Tree)
1. 將原數組所有元素乘以2后得到數組nums2
2. 將nums與nums2合并后進行離散化處理(排序+去重),從實數范圍映射到 [1, len(set(nums + nums2))],記得到的映射為dmap
3. 從右向左遍歷nums2,記當前數字為n,統計(0, dmap[n / 2])的區間和,然后對樹狀數組的dmap[n]位置執行+1操作
【參考答案】