- class Solution:
- def sortArray(self, nums: List[int]) -> List[int]:
- def heapify(nums, parent, arr_size):
- # parent为开始下滤节点索引,p为当前堆大小(决定调整边界)
- x = nums[parent]
- # 下滤, 当左儿子在堆范围内
- while parent * 2 + 1 < arr_size:
- child = parent * 2 + 1
- if child != arr_size-1 and nums[child+1] > nums[child]:
- child += 1
- if nums[child] > x:
- nums[parent] = nums[child]
- parent = child
- else:
- break
- nums[parent] = x
-
- # 构建堆
- n = len(nums)
- for i in range(n//2, -1, -1):
- heapify(nums, i, n) # 建堆时堆大小固定为其容量
- # 迭代删除堆顶元素
- for i in range(n-1, 0, -1):
- # 将堆顶元素取出(直接在末尾存储),把末尾元素放堆顶
- nums[i], nums[0] = nums[0], nums[i]
- heapify(nums, 0, i) # 然后下滤
- return nums