Test case need to be updated or I am wrong?


  • 1
    J

    For this test case:
    [1,1,2,2,3,3, 9]
    and k = 2,
    what's right output ?

    my code got: [1,2,3]
    but the except anster is [1, 2],
    and I GET an AC.
    why?

    my code is as follows:

    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int, int> um;
            for (int i = 0; i < nums.size(); i++)
                um[nums[i]] ++;
            
            map<int, set<int>> r;
            for (auto it=um.begin(); it != um.end(); it++) {
                r[it->second].insert(it->first);
            }
            
            vector<int> ret;
            for (auto rit=r.rbegin(); k>0 && rit != r.rend(); rit++) {
                k -= (rit->second).size();
                for (auto it = (rit->second).begin(); it != (rit->second).end(); it++) {
                    ret.push_back(*it);
                }
            }
            
            return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.