题解 | #输入n个整数,输出其中最小的k个#

输入n个整数,输出其中最小的k个

https://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c

from queue import Queue  # 队列,FIFO
from queue import PriorityQueue  # 优先级队列,优先级高的先输出


def construct_min_heap(nums):
    n = len(nums)
    for i in range((n - 2) // 2, -1, -1):
        shift_down(nums, n, i)


def shift_down(nums: list, n: int, index: int):
    while index < n:
        val = nums[index]
        l_child_index, r_child_index = index * 2 + 1, index * 2 + 2
        l_child_val = 999999999 if l_child_index >= n else nums[l_child_index]
        r_child_val = 999999999 if r_child_index >= n else nums[r_child_index]
        if l_child_val == r_child_val == 999999999:
            break
        min_child_val = min(l_child_val, r_child_val)
        min_child_index = l_child_index if l_child_val < r_child_val else r_child_index
        if val > min_child_val:
            nums[index] = min_child_val
            nums[min_child_index] = val
            index = min_child_index
        else:
            break


def pop_min_heap(nums: list):
    ret = nums[0]
    nums[0] = nums.pop()
    shift_down(nums, len(nums), 0)
    return ret


n, k = [int(i) for i in input().split()]
nums = [int(i) for i in input().split()]
construct_min_heap(nums)
# print(nums)
for i in range(k):
    print(pop_min_heap(nums), end=" ")

全部评论

相关推荐

10-27 17:26
东北大学 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务