Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

347. Top K Frequent Elements #258

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

347. Top K Frequent Elements

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

Example 1

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2

Input: nums = [1], k = 1
Output: [1]

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function(nums, k) {
    const cache = new Map();
    for (let i = 0; i < nums.length; i++) {
        cache.set(nums[i], (cache.get(nums[i]) || 0) + 1);
    }
    const pairs = [...cache.entries()];
    const separator = quickSort(0, pairs.length - 1);
    return pairs.slice(0, separator + 1).map(([num]) => num);

    function quickSort(left, right) {
        if (left >= right) {
            return left;
        }
        const pivotIndex = Math.floor(Math.random() * (right - left + 1) + left);
        const pivotValue = pairs[pivotIndex];
        swap(pivotIndex, right);
        let i = 0;
        let j = -1;
        while(i < right) {
            if (pairs[i][1] >= pivotValue[1]) {
                swap(++j, i);
            }
            i++;
        }
        swap(++j, right);
        if (j + 1 === k) {
            return j;
        } else if (j + 1 < k) {
            return quickSort(j + 1, right);
        } else {
            return quickSort(left, j - 1);
        }
    }
    function swap(x, y) {
        const temp = pairs[x];
        pairs[x] = pairs[y];
        pairs[y] = temp;
    }
};
function topKFrequent(nums: number[], k: number): number[] {
    const cache: Map<number, number> = new Map();
    for (let i = 0; i < nums.length; i++) {
        cache.set(nums[i], (cache.get(nums[i]) || 0) + 1);
    }
    const pairs = [...cache.entries()];
    const separator = quickSort(0, pairs.length - 1);
    return pairs.slice(0, separator + 1).map(([num]) => num);

    function quickSort(left: number, right: number): number {
        if (left >= right) {
            return left;
        }
        const pivotIndex = Math.floor(Math.random() * (right - left + 1) + left);
        const pivotValue = pairs[pivotIndex];
        swap(pivotIndex, right);
        let i = 0;
        let j = -1;
        while(i < right) {
            if (pairs[i][1] >= pivotValue[1]) {
                swap(++j, i);
            }
            i++;
        }
        swap(++j, right);
        if (j + 1 === k) {
            return j;
        } else if (j + 1 < k) {
            return quickSort(j + 1, right);
        } else {
            return quickSort(left, j - 1);
        }
    }
    function swap(x: number, y: number) {
        const temp = pairs[x];
        pairs[x] = pairs[y];
        pairs[y] = temp;
    }
};