题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
左神の超级水王问题
https://www.bilibili.com/video/BV1Bz4y1k7u6?share_source=copy_web\n
代码实现(JAVA)
https://github.com/algorithmzuo/videocode/blob/main/src/videocode/Code01_SuperWaterKing.java
以下是我的C语言code:
/**
*
* @param numbers int整型一维数组
* @param numbersLen int numbers数组长度
* @return int整型
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
int MoreThanHalfNum_Solution(int* numbers, int numbersLen ) {
// write code here
if (numbers == NULL || numbersLen < 1) {
return -1;
}
int mostnum = 0;
int hp = 0;
for (int i = 0; i < numbersLen; i++) {
if (hp == 0) {
mostnum = numbers[i];
hp = 1;
} else if (numbers[i] != mostnum) {
hp--;
} else hp++;
}
if (hp == 0) {
return -1;
}
int cnt = 0;
for (int i = 0; i < numbersLen; i++) {
if (numbers[i] == mostnum) {
cnt++;
}
}
return cnt > (numbersLen >> 1) ? mostnum : -1;
}
