如何使用快速排序找到K个最小值

编程入门 行业动态 更新时间:2024-10-26 14:30:48
本文介绍了如何使用快速排序找到K个最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我对所有值进行排序并选择第一个K值,则问题很简单。但这浪费了太多时间,因为在对整个数组进行排序之前,可能已经对最小的K值进行了排序。我认为解决此问题的方法是在代码中添加一个标志,但是我不知道如何放置该标志来判断最小的k值是否已排序。

The problem is simple if I sort all the values and pick the fist K values. But it wastes too much time because maybe the smallest K values has been sorted before the whole array is sorted. I think the way to solve this problem is to add a flag in the code, but I can not figure out how to put the flag to judge whether the smallest k values has been sort.

推荐答案

您可以使用随机选择算法用O(n)时间解决这个问题。最后,只需将子数组从0返回到k。

You can use random selection algorithm to solve this problem with O(n) time. In the end, just return sub-array from 0 to k.

更多推荐

如何使用快速排序找到K个最小值

本文发布于:2023-11-29 17:40:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647123.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   最小值   快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!