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
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
输入:arr = [3,2,1], k = 2 输出:[1,2] 或者 [2,1]
输入:arr = [0,1,2,1], k = 1 输出:[0]
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
The text was updated successfully, but these errors were encountered:
function getLeastNumbers(arr: number[], k: number): number[] { if (k === 0) { return []; } return quickFind(arr, 0, arr.length - 1, k); }; function quickFind(nums: number[], left: number, right: number, target: number): number[] { const pivotIndex = Math.floor(Math.random() * (right - left + 1) + left); const pivotValue = nums[pivotIndex]; swap(nums, pivotIndex, right); let separator = left - 1; for (let i = left; i < right; i++) { if (nums[i] < pivotValue) { swap(nums, ++separator, i); } } swap(nums, ++separator, right); if (separator === target - 1) { return nums.slice(0, separator + 1); } else if (separator < target - 1) { return quickFind(nums, separator + 1, right, target); } else { return quickFind(nums, left, separator - 1, target); } } function swap(nums: number[], x: number, y: number) { const temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; }
Sorry, something went wrong.
No branches or pull requests
剑指 Offer 40. 最小的k个数
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
Example 1
Example 2
Note
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
The text was updated successfully, but these errors were encountered: