We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接
const getLeastNumbers = function(arr, k) { return arr.sort((a, b) => a - b).slice(0, k) }
我们可以借助大顶堆,因为大顶堆的节点值都大于等于其左右子节点的值,并且堆顶的元素最大。
JavaScript 需要自己构建大顶堆,可以参考:https://juejin.cn/post/6932482325159067656
const getLeastNumbers = function(arr, k) { const heap = [,] let i = 0 while (i < k) { heap.push(arr[i++]) } buildHeap(heap, k) for (let i = k; i < arr.length; i++) { if (heap[1] > arr[i]) { heap[1] = arr[i] heapify(heap, k, 1) } } heap.shift() return heap } const buildHeap = (arr, k) => { if (k === 1) return for (let i = Math.floor(k / 2); i >= 1 ; i--) { heapify(arr, k, i) } } const heapify = (arr, k, i) => { while (true) { let maxIndex = i if (2 * i <= k && arr[i] < arr[2 * i]) { maxIndex = 2*i } if (2 * i + 1 <= k && arr[maxIndex] < arr[2 * i + 1]) { maxIndex = 2 * i + 1 } if (maxIndex !== i) { swap(arr, i, maxIndex) i = maxIndex } else { break } } } const swap = (arr, i , j) => { let temp = arr[i] arr[i] = arr[j] arr[j] = temp }
数组范围有限时,要想到用计数排序。
用一个新的数组统计每个数字出现的次数,然后控制输出前 k 个即可。
const getLeastNumbers = function(arr, k) { const countingSort = (arr, maxValue, k) => { const len = arr.length const bucket = new Array(maxValue + 1) const bucketLen = maxValue + 1 let sortedIndex = 0 for (let i = 0; i < len; i++) { if (!bucket[arr[i]]) { bucket[arr[i]] = 0 } bucket[arr[i]]++ } const res = [] for (let j = 0; j < bucketLen; j++) { while (bucket[j]-- > 0 && sortedIndex < k) { res[sortedIndex++] = j } if (sortedIndex === k) { break } } return res } return countingSort(arr, 10000, k) }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接
数组 sort 排序
大顶堆
我们可以借助大顶堆,因为大顶堆的节点值都大于等于其左右子节点的值,并且堆顶的元素最大。
JavaScript 需要自己构建大顶堆,可以参考:https://juejin.cn/post/6932482325159067656
计数排序
数组范围有限时,要想到用计数排序。
用一个新的数组统计每个数字出现的次数,然后控制输出前 k 个即可。
The text was updated successfully, but these errors were encountered: