import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
/**
方法一: 我认为是最简单的,不就是找中位数吗,因此数量比一半要多,直接排序后选中位数返回即可,秒做
一般做数组的题目,我觉得题目没有强制说不用排序,一般可以用排序来简化做题
*/
public int majority_cow (int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
/**
方法二:遍历+模拟 这个需要数学去想一下,不如第一种简便,当然可能有些人想不到排序,那就模拟
*/
public int majority_cow(int[] nums) {
int count = 0; // 当前候选牛种的计数
int candidate = 0; // 当前候选牛种
for (int num : nums) {
if (count == 0) {
candidate = num;
count = 1;
} else if (candidate == num) {
count++;
} else {
count--;
}
}
// 最终的候选牛种一定是优势牛种
return candidate;
}
}
本题知识点:
1.数组排序(快速排序)
2.数组遍历
3.数学模拟
本题思路分析:
1.明确众数,题目要求找一半以上的数量,那么这个牛种必然是中位数
2.方法一:直接排序,然后取中间值返回即可
3.方法二:模拟,当牛种计数为0时,说明还未开始或者是两个牛种数量相同,那么必然不是这两个,因为答案只有一个,且数量超过一半,如果候选牛种等于遍历的牛种,说明数量+1,反之数量-1,最后返回数量即可

京公网安备 11010502036488号