Skip to content

Commit

Permalink
[python]LCR 170. 交易逆序对的总数
Browse files Browse the repository at this point in the history
  • Loading branch information
Huauauaa committed Aug 21, 2024
1 parent f4c5e48 commit dd2b1a7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# code-every-day

## 算法

- [逆序对/归并排序](./notes/逆序对.md)
4 changes: 4 additions & 0 deletions notes/逆序对.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# 逆序对

- [题解 1](https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solutions/622496/jian-zhi-offer-51-shu-zu-zhong-de-ni-xu-pvn2h)
- [题解 2](https://www.bilibili.com/video/BV1Qk4y1r7u5/?spm_id_from=333.337.search-card.all.click&vd_source=fa26c1805b6d94a7f2b5002f0ae9a401)
37 changes: 37 additions & 0 deletions src/leetcode/LCR00170.shu-zu-zhong-de-ni-xu-dui-lcof/170.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from typing import List


class Solution:
def reversePairs(self, record: List[int]) -> int:
"""
https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/description/
"""
tmp = [0] * len(record)

def merge_sort(l, r):
if l >= r:
return 0
m = (l + r) >> 1
res = merge_sort(l, m) + merge_sort(m + 1, r)

i, j = l, m + 1
tmp[l : r + 1] = record[l : r + 1]
for k in range(l, r + 1):
if i == m + 1:
record[k] = tmp[j]
j += 1
elif j == r + 1 or tmp[i] <= tmp[j]:
record[k] = tmp[i]
i += 1
else:
record[k] = tmp[j]
j += 1
res += m - i + 1
return res

return merge_sort(0, len(record) - 1)


if __name__ == "__main__":
res = Solution().reversePairs([9, 7, 5, 4, 6])
print(res)

0 comments on commit dd2b1a7

Please sign in to comment.