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
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Input: nums = [1], k = 1 Output: [1]
The text was updated successfully, but these errors were encountered:
/** * @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; } };
Sorry, something went wrong.
No branches or pull requests
347. Top K Frequent Elements
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
Example 1
Example 2
Note
The text was updated successfully, but these errors were encountered: