Leetcode 2190. Most Frequent Number Following Key In an Array
You are given an integer array nums
and an integer key
, in which nums[i]
is preceded by nums[i-1]
in the array. Your task is to find the most frequent number immediately following an occurrence of key
in the array. If there are multiple answers, it is sufficient to return any one of the most frequent numbers.
nums
can contain negative numbers.key
is not present in the array?
key
in the array.key
, returning any one of them is acceptable.key
.key
.#include <vector>
#include <unordered_map>
using namespace std;
int mostFrequentFollowingKey(vector<int>& nums, int key) {
unordered_map<int, int> frequency_map;
for (size_t i = 0; i < nums.size() - 1; ++i) {
if (nums[i] == key) {
int follower = nums[i + 1];
frequency_map[follower]++;
}
}
int most_frequent = -1;
int max_count = 0;
for (const auto& entry : frequency_map) {
if (entry.second > max_count) {
max_count = entry.second;
most_frequent = entry.first;
}
}
return most_frequent;
}
nums
.This solution efficiently handles the problem within the given constraints, ensuring minimal time and space overhead.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?