题解 | #农场牛群众数#

农场牛群众数

https://www.nowcoder.com/practice/de4e4039a45247579ffeef81ccf44266

知识点

哈希

解题思路

遍历数组,用ans保存当前编号最大的众数,max保存最多出现的次数,使用map来保存每个数出现的次数。

在遍历过程中,将num出现的次数保存到哈希中,如果出现次数大于ans,则它是出现最多的数,更新max和ans,以此类推。

Java题解

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型一维数组
     */
    public int[] findMode (int[] nums) {
        // write code here
        int n = nums.length;
        int[] ans = new int[n];
        Map<Integer,Integer> map = new HashMap<>();
        int max = 0;
        int bianhao = 0;
        int i = 0;
        for(int num : nums){
            int temp = map.getOrDefault(num,0) + 1;
            map.put(num,temp);
            if(temp > max || (temp == max && num > bianhao)){
                ans[i] = num;
                max = temp;
                bianhao = num;
            } else {
                ans[i] = bianhao;
            }
            i++;
        }
        return ans;

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务