题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if (array == null || array.length < 1) {
return -1;
}
int n = array.length;
int cand = 0;
int cnt = 0;
for (int num : array) {
if (cnt == 0) {
cand = num;
cnt++;
} else if (cand == num) {
cnt++;
} else {
cnt--;
}
}
cnt = 0;
for (int num : array) {
if (cand == num) {
cnt++;
}
}
return cnt > n / 2 ? cand : -1;
}
}
查看23道真题和解析

顺丰集团工作强度 350人发布