题解 | #最小的K个数#

最小的K个数

https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param input int整型一维数组 
 * @param k int整型 
 * @return int整型一维数组
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
/**
 * 解题思路: 大顶堆(leetcode)
 * **************************************************************************
 */
var GetLeastNumbers_Solution = function(nums, k) {
    // 边界情况
    if (nums.length <= 0) return []
    if (k <= 0) return []
    if (nums.length <= k) return nums
    const maxK = nums.length - k
    // 非边界情况
    heapSrot(nums, maxK)
    return nums.slice(0, k)
};

function heapSrot(nums, k) {
    buildHeap(nums)
    let count = 0
    for (let i = nums.length - 1; i >= 0; i--) {
        swap(nums, 0, i)
        count += 1
        if (k === count) {
            return nums[nums.length - k]
        }
        heapify(nums, i, 0)
    }
}
function buildHeap(nums) {
    const lastChild = nums.length - 1
    const lastChildParent = Number.parseInt((lastChild - 1) / 2)
    for (let i = lastChildParent; i >= 0; i--) {
        heapify(nums, nums.length, i)
    }
}
/**
 */
function heapify(nums, n, i) {
    if  (i >= n) return // 加的
    const childLeft = 2 * i + 1
    const childRight = 2 * i + 2
    let maxIndex = i
    if (childLeft < n && nums[childLeft] > nums[maxIndex]) {
        maxIndex = childLeft
    }
    if (childRight < n && nums[childRight] > nums[maxIndex]) {
        maxIndex = childRight
    }
    if (i !== maxIndex) {
        swap(nums, i, maxIndex)
        heapify(nums, n, maxIndex) // !!!这块要注意
    }
}

function swap(nums, i , j) {
    const temp = nums[i]
    nums[i] = nums[j]
    nums[j] = temp
}

module.exports = {
    GetLeastNumbers_Solution : GetLeastNumbers_Solution
};

全部评论

相关推荐

昨天 23:26
河南大学 Java
双非本,刚学完Redis,项目只有外卖和点评,八股没准备,算法只有lqb省一,感觉敲的项目也是一言难尽没怎么吸收。怎么你们都有实习了
大牛之途:27急个锤子,你投日常实习最好的时间就是9,10月份,那时候暑期实习都结束了,正是缺人的时候。这份日常又能给你的暑期实习增加竞争力,暑期找的好了秋招也不怕了,都是环环相扣的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务