class Solution:
def reversePairs(self, nums: List[int]) -> int:
n = len(nums)
copy = sorted(nums)
bitTree = [0] *(n+1)
def update(i):
while i > 0:
bitTree[i] += 1
i-=i&-i
def getCnt(i):
sm = 0
while i < n+1:
sm +=bitTree[i]
i+=i&-i
return sm
res = 0
for i in nums:
res += getCnt(bisect.bisect_left(copy, i*2+1)+1)
update(bisect.bisect_left(copy, i)+1)
return res
class Solution:
def reversePairs(self, nums: List[int]) -> int:
n = len(nums)
copy = sorted(nums)
bitTree = [0] *(n+1)
def update(i):
while i < n+1:
bitTree[i] += 1
i+=i&-i
def getCnt(i):
sm = 0
while i >0:
sm += bitTree[i]
i-=i&-i
return sm
res = 0
for i in nums:
res += getCnt(n) - getCnt(bisect.bisect_left(copy, i*2+1)) #所有2x+1 - n之间的数都,>2x+1的所有数,不是一个数。
update(bisect.bisect_left(copy, i)+1)
return res
分治
左右段mergesory后,左半端和右半段比较得count。同时左右半段sort merge
class Solution:
def reversePairs(self, nums: List[int]) -> int:
def mergeSort(s,e):
if s >= e:
return 0
mid = (s+e)//2
res = mergeSort(s,mid) + mergeSort(mid+1,e)
i,j,k =0,mid+1,mid+1
temp=[]
for i in range(s,mid+1):
while j <=e and nums[i] > nums[j]*2:
j += 1
res+=(j-mid-1)
while k <=e and nums[i] >= nums[k]:
temp.append(nums[k])
k +=1
temp.append(nums[i])
nums[s:s+len(temp)] = temp[:]
return res
return mergeSort(0,len(nums)-1)