题解 | #农场牛群众数#
农场牛群众数
https://www.nowcoder.com/practice/de4e4039a45247579ffeef81ccf44266
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型一维数组
*/
//空间复杂度:O(n),其中n为nums.length
//时间复杂度: O(n),其中n为nums.length
/**
整体思路:
用map记录各元素出现的次数,max记录当前众数,每次for循环map加入一个元素,如果当前众数比现在的元素出 现次数少,或者次数一样但是众数比当前元素小,则更新max,将max记录到res数组中返回.
*/
public int[] findMode (int[] nums) {
// write code here
HashMap<Integer , Integer> map = new HashMap<>();
int max = nums[0];
int len = nums.length;
int[] res = new int[len];
for (int i = 0; i < len; i++) {
map.put(nums[i] , map.getOrDefault(nums[i] , 0) + 1);
if(map.get(nums[i]) > map.get(max) || map.get(nums[i]) == map.get(max) && nums[i] > max)
max = nums[i];
res[i] = max;
}
return res;
}
}
查看19道真题和解析
巨人网络公司福利 91人发布