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

牛客网: BM46

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

思路: 使用快排思想,low = 0, high = n - 1,在low, high之间调整元素位置(使有和同向left=low,right=low双指针或left=low,right=high-1反向双指针),以numhigh为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]
}
相关推荐
Nuanyt4 天前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针
Nuanyt12 天前
LeetCode Hot 100 · 双指针 3 题 Java
java·笔记·算法·leetcode·双指针
Tsuki_tl13 天前
【优选算法 — 双指针】经典例题题解+算法总结
算法·蓝桥杯·力扣·刷题·双指针·1024程序员节·优选算法
2501_9339232515 天前
双指针算法:移动零+复写零(Java)
数据结构·算法·双指针
Tsuki_tl15 天前
【优选算法:双指针】——复写零题解
java·c++·算法·leetcode·数组·双指针·复写零
lvwangshu16 天前
P17723 [SCP-S 2026] 函数 / func 题解
题解·双指针·技巧·性质题·思维好题·推导题
yi0111 个月前
LeetCode 424. 替换后的最长重复字符|不定长滑动窗口:如何判断窗口是否合法?
笔记·python·算法·leetcode·双指针·滑动窗口
yi0111 个月前
LeetCode 3. 无重复字符的最长子串|不定长滑动窗口:什么时候更新最大值?
笔记·python·算法·leetcode·双指针·滑动窗口
yi0111 个月前
DAY24: LeetCode 167:两数之和 II|从暴力枚举到左右双指针
笔记·python·算法·leetcode·二分查找·双指针
yi0111 个月前
LeetCode 15:三数之和|排序 + 双指针,如何避免重复答案?
笔记·python·算法·leetcode·双指针