添加了python版本代码

为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
goodyong
2021-07-05 22:25:41 +08:00
parent a503e97f11
commit 4e661354d4
16 changed files with 1088 additions and 83 deletions

View File

@@ -40,6 +40,8 @@
是不是很容易理解啊那我们直接看代码吧仅仅是在归并排序的基础上加了几行代码
Java Code:
```java
class Solution {
private int count;
@@ -95,3 +97,56 @@ class Solution {
}
```
Python Code:
```python
from typing import List
class Solution:
count = 0
def reversePairs(self, nums: List[int])->int:
self.count = 0
self.merge(nums, 0, len(nums) - 1)
return self.count
def merge(self, nums: List[int], left: int, right: int):
if left < right:
mid = left + ((right - left) >> 1)
self.merge(nums, left, mid)
self.merge(nums, mid + 1, right)
self.mergeSort(nums, left, mid, right)
def mergeSort(self, nums: List[int], left: int, mid: int, right: int):
temparr = [0] * (right - left + 1)
temp1 = left
temp2 = mid + 1
index = 0
while temp1 <= mid and temp2 <= right:
# 这里需要防止溢出
if nums[temp1] > 2 * nums[temp2]:
self.count += mid - temp1 + 1
temp2 += 1
else:
temp1 += 1
# 记得归位我们还要继续使用
temp1 = left
temp2 = mid + 1
# 归并排序
while temp1 <= mid and temp2 <= right:
if nums[temp1] <= nums[temp2]:
temparr[index] = nums[temp1]
index += 1
temp1 += 1
else:
temparr[index] = nums[temp2]
index += 1
temp2 += 1
# 照旧
if temp1 <= mid:
temparr[index: index + mid - temp1 + 1] = nums[temp1: temp1 + mid - temp1 + 1]
if temp2 <= right:
temparr[index: index + right - temp2 + 1] = nums[temp2: temp2 + right - temp2 + 1]
nums[left: left + right- left + 1] = temparr[0: right - left + 1]
```