2190. Most Frequent Number Following Key In an Array Easy

@problem@discussion
#Array#Hash Table#Counting



1/**
2 * [2190] Most Frequent Number Following Key In an Array
3 *
4 * You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.
5 * For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that:
6 * 
7 * 0 <= i <= nums.length - 2,
8 * nums[i] == key and,
9 * nums[i + 1] == target.
10 * 
11 * Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.
12 *  
13 * Example 1:
14 * 
15 * Input: nums = [1,100,200,1,100], key = 1
16 * Output: 100
17 * Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.
18 * No other integers follow an occurrence of key, so we return 100.
19 * 
20 * Example 2:
21 * 
22 * Input: nums = [2,2,2,2,3], key = 2
23 * Output: 2
24 * Explanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.
25 * For target = 3, there is only one occurrence at index 4 which follows an occurrence of key.
26 * target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.
27 * 
28 *  
29 * Constraints:
30 * 
31 * 2 <= nums.length <= 1000
32 * 1 <= nums[i] <= 1000
33 * The test cases will be generated such that the answer is unique.
34 * 
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/
39// discuss: https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42use std::collections::HashMap;
43
44impl Solution {
45    pub fn most_frequent(nums: Vec<i32>, key: i32) -> i32 {
46        let mut map: HashMap<i32, i32> = HashMap::new();
47        for i in 1..nums.len() {
48            if key == nums[i - 1] {
49                map.entry(nums[i]).and_modify(|x| {*x += 1;}).or_insert(1);
50            }
51        }
52        let (mut max, mut value) = (0, 0);
53        for (k, v) in map {
54            if v > max {
55                value = k;
56                max = v;
57            }
58        }
59        value
60    }
61}
62
63// submission codes end
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn test_2190() {
71        assert_eq!(Solution::most_frequent(vec![1,100,200,1,100], 1), 100);
72        assert_eq!(Solution::most_frequent(vec![2,2,2,2,2,3], 2), 2);
73    }
74}
75


Back
© 2025 bowen.ge All Rights Reserved.