Skip to content

Bug Report for top-k-elements-in-list #6177

Open

Description

@AndyDough

Bug Report for https://neetcode.io/problems/top-k-elements-in-list

When I tried to use a reverse_view in a for range loop in c++, #include <ranges> isn't auto included
Easy solution add #include <ranges> to list of common includes

My solution:

#include <range> // Auto include for reverse forrange loops

    vector<int> topKFrequent(vector<int>& nums, int k) {
        std::vector<int> answer{};
        if (nums.empty()) {
            return answer;
        }

        std::unordered_map<int, int> count{};
        for (const auto &e : nums) {
            count[e] += 1;
        }

        // Change buckets to a vector of vectors to handle duplicate frequencies
        std::vector<std::vector<int>> buckets(nums.size() + 1);
        for (const auto &e : count) {
            buckets[static_cast<std::size_t>(e.second)].push_back(e.first);
        }

        for (const auto &element : std::views::reverse(buckets)) {
            for (const auto &inner : element) {
                answer.push_back(inner);
                if (static_cast<int>(answer.size()) == k) {
                    return answer;
                }
            }
        }

        return answer; 
    }

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions