剑指Offer-51 数组中的逆序对
程序员文章站
2022-07-10 12:16:40
...
题目:
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
样例
输入:[1,2,3,4,5,6,0]
输出:6
解答:
class Solution(object):
def inversePairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return 0
count = 0
mid = int(len(nums)/2)
self.copy = nums[:]
count = self.inversePairsCore(nums, 0, len(nums) - 1)
return count
def inversePairsCore(self, seq, start, end):
if start == end:
return 0
mid = int((start + end)/2)
count = 0
count += self.inversePairsCore(seq, start, mid) + self.inversePairsCore(seq, mid + 1, end)
i, j = mid, end
index = end
while(i >= start and j >= mid + 1):
if seq[i] > seq[j]:
self.copy[index] = seq[i]
count += j - mid
i -= 1
else:
self.copy[index] = seq[j]
j -= 1
index -= 1
while(i >= start):
self.copy[index] = seq[i]
index -= 1
i -= 1
while(j >= mid + 1):
self.copy[index] = seq[j]
index -= 1
j -= 1
for i in range(start, end + 1):
seq[i] = self.copy[i]
return count
上一篇: 【剑指Offer】51、数组中的逆序对