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

Top K Frequent Elements #19

Open
cheatsheet1999 opened this issue Sep 8, 2021 · 0 comments
Open

Top K Frequent Elements #19

cheatsheet1999 opened this issue Sep 8, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

cheatsheet1999 commented Sep 8, 2021

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Screen Shot 2021-09-07 at 6 43 26 PM

var topKFrequent = function(nums, k) {
    const map = new Map();
    const res = [];
    const freqArr = [];
    
    for(let num of nums) {
        map.set(num, (map.get(num) || 0) + 1);
    }
    
    for(let [num, freq] of map) {
        freqArr[freq] = (freqArr[freq] || new Set()).add(num);
    }
    
    for(let i = freqArr.length - 1; i >= 0; i--) {
        // if(freqArr[I]) is necessary because not all index has element attached to it
        if(freqArr[i]) res.push(...freqArr[i]);
        if(res.length === k) break;
    }
    return res;
};

Time complexity : O(n)

kyxg added a commit to kyxg/FrontEndCollection that referenced this issue Jan 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant