题解 | #草原上优势牛种#
草原上优势牛种
https://www.nowcoder.com/practice/178705f48adc4e39ac8537a22e8941cd
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int majority_cow (int[] nums) {
// write code here
// 定义一个数组,用于记录nums数组中每个整数出现的次数
// 考虑到nums中数值的取值返回,以及可能存在负数,所以cnt数组长度定义为100000
int[] cnt = new int[100000];
// 遍历原数组
for (int x : nums) {
// +50000 避免x位负整数
cnt[x + 50000]++;
// ++ 计数,并判断是否超过原数组长度的一半,如果是则返回x
if (cnt[x + 50000]++ >= nums.length / 2) return x;
}
// 如果没找到返回-1
return -1;
}
}
#数组计数#线性表基础 文章被收录于专栏
链表、递归、栈
巨人网络成长空间 53人发布