算法 最小的K个数-(快速排序、双指针)

牛客网: BM46

题目: 找出数组最小的k个数

思路: 使用快排思想,low = 0, high = n - 1,在low, high之间调整元素位置(使有和同向left=low,right=low双指针或left=low,right=high-1反向双指针),以num[high]为pivot,比pivot小的放左历,比pivot大的放右边,最后将pivot调整至中间,当pivot位置坐标为k-1时,则pivot及其左边的所有元素均为最小的k个数;pivot坐标大于k-1时,调整high=pivot坐标-1;pivot坐标小于k-1时,调整low = pivot坐标+1,直至low 不再小于high,停止。

代码:

Go 复制代码
// go

package main
// import "fmt"

/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 
* @param input int整型一维数组 
* @param k int整型 
* @return int整型一维数组
*/
func GetLeastNumbers_Solution( input []int ,  k int ) []int {
    // write code here
    if len(input) == 0 || len(input) < k || k == 0 {
        return []int{}
    }
    low := 0
    high := len(input) - 1
    for low < high {
        // 同向双指针
        left := low
        right := low
        pivot := input[high]
        for right < high {
            if input[right] < pivot {
                input[left], input[right] = input[right], input[left]
                left++
                right++
            } else {
                right++
            }
        }
        input[left], input[high] = input[high], input[left]
        if left == k - 1 {
            break
        } else if left > k - 1 {
            high = left - 1
        } else {
            low = left + 1
        }
    }
    return input[:k]
}
相关推荐
递归尽头是星辰4 天前
双指针与滑动窗口算法精讲:从原理到高频面试题实战
算法·双指针·滑动窗口·子串/子数组问题
pusue_the_sun4 天前
每日算法题推送
算法·双指针
爱编程的化学家5 天前
代码随想录算法训练营第六天 - 哈希表2 || 454.四数相加II / 383.赎金信 / 15.三数之和 / 18.四数之和
数据结构·c++·算法·leetcode·双指针·哈希
林木辛7 天前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
3Cloudream8 天前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
Q741_14721 天前
C++ 力扣 76.最小覆盖子串 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
源代码•宸22 天前
Leetcode—1163. 按字典序排在最后的子串【困难】
经验分享·算法·leetcode·双指针
KarrySmile23 天前
Day8--HOT100--160. 相交链表,206. 反转链表,234. 回文链表,876. 链表的中间结点
数据结构·算法·链表·双指针·快慢指针·hot100·灵艾山茶府
迷鹿鲲1 个月前
最短无序连续子数组+双指针
双指针
Q741_1471 个月前
C++ 力扣 438.找到字符串中所有字母异位词 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口