题解 | #草原上优势牛种#
草原上优势牛种
https://www.nowcoder.com/practice/178705f48adc4e39ac8537a22e8941cd
题目考察的知识点是:
数组、循环。
题目解答方法的文字分析:
必然存在那个半数以上的数,所以我们理解成互相攻击问题即可。维护当前次数以及当前的编号,当出现不同编号时,次数--,如果次数小于等于0,那么更新编号。最后留下来的那个编号即为出现次数半数以上的数。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int majority_cow (int[] nums) {
// write code here
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;
}
}
#题解#