You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 (constauto &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 (constauto &e : count) {
buckets[static_cast<std::size_t>(e.second)].push_back(e.first);
}
for (constauto &element : std::views::reverse(buckets)) {
for (constauto &inner : element) {
answer.push_back(inner);
if (static_cast<int>(answer.size()) == k) {
return answer;
}
}
}
return answer;
}
Activity