题目:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
限制:
- 0 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof
方法一:归并排序
在排序中计数,如果有前后两段排序好的序列,记录后段序列的各个元素越过前段序列元素个数的和,为逆序数。
class Solution:
def reversePairs(self, nums: List[int]) -> int:
l = len(nums)
if l<2:
return 0
counting, nums = self.sort_partiton(nums)
print(nums)
return counting
def sort_partiton(self, nums):
sort_counting = 0
l = len(nums)
if l == 2:
if nums[0]>nums[1]:
sort_counting+=1
c = nums[0]
nums[0]=nums[1]
nums[1]=c
return sort_counting, nums
elif l < 2:
return 0,nums
else:
middle = l//2
x1, nums1 = self.sort_partiton(nums[0:middle])
x2, nums2 = self.sort_partiton(nums[middle:l])
sort_counting += x1
sort_counting += x2
l1 = middle
l2 = l-middle
i = 0
j = 0
for n in range(l):
if nums1[i]<=nums2[j]:
nums[n] = nums1[i]
i+=1
else:
nums[n] = nums2[j]
j+=1
sort_counting += (l1-i)
if i==l1 or j==l2:
break
if i==l1:
nums[n+1:] = nums2[j:]
elif j==l2:
nums[n+1:] = nums1[i:]
return sort_counting, nums

1717

被折叠的 条评论
为什么被折叠?



