Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sort-an-array.py 2.37 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-04-22 04:35 +08:00 . Update sort-an-array.py
# Time: O(nlogn)
# Space: O(n)
# merge sort solution
class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def mergeSort(start, end, nums):
if end - start <= 1:
return
mid = start + (end - start) / 2
mergeSort(start, mid, nums)
mergeSort(mid, end, nums)
right = mid
tmp = []
for left in xrange(start, mid):
while right < end and nums[right] < nums[left]:
tmp.append(nums[right])
right += 1
tmp.append(nums[left])
nums[start:start+len(tmp)] = tmp
mergeSort(0, len(nums), nums)
return nums
# Time: O(nlogn), on average
# Space: O(logn)
import random
# quick sort solution
class Solution2(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def kthElement(nums, left, mid, right, compare):
def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
new_pivot_idx = left
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in xrange(left, right):
if compare(nums[i], nums[right]):
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
right -= 1
while left <= right:
pivot_idx = random.randint(left, right)
new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
if new_pivot_idx == mid - 1:
return
elif new_pivot_idx > mid - 1:
right = new_pivot_idx - 1
else: # new_pivot_idx < mid - 1.
left = new_pivot_idx + 1
def quickSort(start, end, nums):
if end - start <= 1:
return
mid = start + (end - start) / 2
kthElement(nums, start, mid, end, lambda a, b: a < b)
quickSort(start, mid, nums)
quickSort(mid, end, nums)
quickSort(0, len(nums), nums)
return nums
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助