劍指Offer-51 陣列中的逆序對
阿新 • • 發佈:2018-12-10
題目:
在陣列中的兩個數字如果前面一個數字大於後面的數字,則這兩個數字組成一個逆序對。輸入一個數組,求出這個陣列中的逆序對的總數。
樣例
輸入:[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