Leetcode每日一题
题目链接: 493. 翻转对
难度: 困难
解题思路: 这道题可以看作是求逆序对的变种题。将题中的条件(如果 i < j 且 nums[i] > 2*nums[j])看作是逆序对。可以用线段树/树状数组或者是归并方法用O(nlogn)的时间复杂度求得。但是对于此题还需要进行离散化,来记录当前值和它的二倍的值(这样可以直接在离散化数组中找到2倍的值)。可以得到一个整体的大小信息。用线段树记录当前值所在整体的位置(大小)的数量。然后进行查询时查找 (当前值*2,结束位置(最大值)] 的数量(左开右闭)。动态的更新并查找,直到更新完所有值。
题解:
class Solution:
def reversePairs(self, nums: List[int]) -> int:
#
# 离散化
#
sorted_nums = list(nums)
# 加入二倍的值
for example in set(nums):
sorted_nums.append(example * 2)
sorted_nums = list(set(sorted_nums))
sorted_nums.sort()
# 记录位置所有值的位置索引(离散化)
support = dict()
for i in range(len(sorted_nums)):
support[sorted_nums[i]] = i + 1
length = len(support)
tree = [0] * (length + 1)
#
# 树状数组操作
#
def lowbit(x):
return x & (-x)
def update(index, val):
while index <= length:
tree[index] += val
index += lowbit(index)
def query(index):
ans = 0
while index != 0:
ans += tree[index]
index -= lowbit(index)
return ans
#
# 计算
#
ans = 0
for i in range(len(nums)):
left = support[nums[i] * 2]
right = length
ans += query(right) - query(left)
update(support[nums[i]], 1)
return ans