算法 最小的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]
}
相关推荐
量子炒饭大师21 小时前
【优化算法】滑动窗口的「义体化」重构 ——【滑动窗口】何为滑动窗口?滑动窗口算法的核心目的是什么?
c++·算法·重构·优化算法·双指针·滑动窗口
Tisfy1 天前
LeetCode 2540.最小公共值:双指针(O(m+n))
算法·leetcode·题解·双指针
handler015 天前
滑动窗口(同向双指针)算法:模板与例题解析
c语言·c++·笔记·算法·蓝桥杯·双指针·滑动窗口
量子炒饭大师12 天前
【优化算法】双指针算法的「义体化」重构 ——【双指针】双指针算法中的指针是如何定义的?如何使用它进行一些简单的算法?
c++·算法·重构·优化算法·双指针
量子炒饭大师15 天前
【优化算法:双指针算法刷题宝典】—— 三数之和
算法·优化算法·双指针·三数之和
qeen871 个月前
【算法笔记】双指针及其经典例题解析
c++·笔记·算法·双指针
李日灐1 个月前
【优选算法3】二分查找经典算法面试题
开发语言·c++·后端·算法·面试·二分查找·双指针
小肝一下1 个月前
每日两道力扣,day7
数据结构·c++·算法·leetcode·双指针·hot100·接雨水,四数之和
小肝一下1 个月前
每日两道力扣,day6
数据结构·c++·算法·leetcode·双指针·hot100
Byte不洛1 个月前
LeetCode双指针经典题
c++·算法·leetcode·双指针