算法 最小的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]
}
相关推荐
不吃粑粑-17 小时前
环形数组上的滑动窗口,取模题型trick abc440_c C - Striped Horse
双指针
老鼠只爱大米1 天前
LeetCode算法题详解 42:接雨水
leetcode·动态规划·双指针·单调栈·接雨水·雨水收集
老鼠只爱大米1 天前
LeetCode算法题详解 11:盛最多水的容器
leetcode·面试题·双指针·盛最多水的容器·面积最大化
汉克老师2 天前
GESP2025年12月认证C++八级真题与解析(判断题8-10)
c++·快速排序··lcs·gesp八级·gesp8级
老鼠只爱大米3 天前
LeetCode算法题详解 15:三数之和
算法·leetcode·双指针·三数之和·分治法·three sum
老鼠只爱大米3 天前
LeetCode算法题详解 283:移动零
算法·leetcode·双指针·快慢指针·移动零·move zeroes
田梓燊4 天前
leetcode 有序数组的平方
双指针
无尽的罚坐人生6 天前
hot 100 42. 接雨水
数据结构·算法·leetcode·动态规划··双指针
羑悻的小杀马特6 天前
LeetCode 42接雨水全解:暴力超时→DP降维打击→双指针极限压缩空间→单调栈栈式凹槽定位,全景式解析算法优化路径
算法·leetcode·职场和发展·动态规划·双指针·单调栈·接雨水
不会c嘎嘎9 天前
数据结构 -- 常见的八大排序算法
数据结构·c++·算法·排序算法·面试题·快速排序