0
点赞
收藏
分享

微信扫一扫

LeetCode 6024. 数组中紧跟 key 之后出现最频繁的数字

小时候是个乖乖 2022-03-11 阅读 57
LeetCode

题目链接:

力扣icon-default.png?t=M1L8https://leetcode-cn.com/contest/biweekly-contest-73/problems/most-frequent-number-following-key-in-an-array/

class Solution {
    public int mostFrequent(int[] nums, int key) {
Map<Integer, Integer> map = new HashMap<>();
        int n = nums.length;
        for(int i = 0; i < n - 1; i ++){
            if(nums[i] == key){
                if(map.containsKey(nums[i + 1])){
                    map.put(nums[i + 1], map.get(nums[i + 1]) + 1);
                }else{
                    map.put(nums[i + 1], 1);
                }
            }
        }
        int cnt = -1;
        int ans = key;
        for(Map.Entry<Integer, Integer> entry: map.entrySet()){
            if(entry.getValue() > cnt){
                cnt = entry.getValue();
                ans = entry.getKey();
            }
        }
        return ans;
    }
}

 

举报

相关推荐

数组中只出现一次的数字

0 条评论