Example
Example 1:
Input: nums = [1,100,200,1,100], key = 1
Output: 100
Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.
No other integers follow an occurrence of key, so we return 100.
Example 2:
Input: nums = [2,2,2,2,3], key = 2
Output: 2
Explanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.
For target = 3, there is only one occurrence at index 4 which follows an occurrence of key.
target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.
Code
class Solution {
public:
int mostFrequent(vector<int>& nums, int key) {
array<int, 1001> arr{};
for (int i = 0; i < nums.size()-1; i++) {
if (nums[i] == key) {
arr[nums[i+1]]++;
}
}
int max_index = 0;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] > arr[max_index])
max_index = i;
}
return max_index;
}
}
Logic
- Only count the numbers that come immediately after the
key
- Instead of using a
std::map (time complexity for most operations is O(n log n)), just use an array as a lookup table since the size of elements is around 1000