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