Skip to content
New issue

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

剑指 Offer 40. 最小的k个数 #76

Open
Tcdian opened this issue Mar 20, 2020 · 1 comment
Open

剑指 Offer 40. 最小的k个数 #76

Tcdian opened this issue Mar 20, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 20, 2020

剑指 Offer 40. 最小的k个数

输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

Example 1

输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]

Example 2

输入:arr = [0,1,2,1], k = 1
输出:[0]

Note

  • 0 <= k <= arr.length <= 10000
  • 0 <= arr[i] <= 10000
@Tcdian Tcdian changed the title 《剑指 Offer(第 2 版)》40. 最小的k个数 剑指 Offer 40. 最小的k个数 Jun 30, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Jul 29, 2020

Solution

  • TypeScript Solution
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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant