leetcode912 python
时间: 2023-10-15 21:25:40 浏览: 172
LeetCode 912题是关于排序数组的问题。以下是一个用Python解决该问题的示例代码:
```python
class Solution:
def sortArray(self, nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left_half = nums[:mid]
right_half = nums[mid:]
left_half = self.sortArray(left_half)
right_half = self.sortArray(right_half)
return self.merge(left_half, right_half)
def merge(self, left, right):
merged = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
while i < len(left):
merged.append(left[i])
i += 1
while j < len(right):
merged.append(right[j])
j += 1
return merged
```
这个解法使用了归并排序的思想,在每一次递归中将数组一分为二,然后合并两个有序数组。最终得到一个排序好的数组。
阅读全文