题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字;
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0;
解题思路
使用摩尔投票算法来解决这个问题,可以是问题的时间和空间复杂度均为O(n);
使用 cnt 来统计一个元素出现的次数,当遍历到的元素和当前统计的元素不相等时,令 cnt--;
如果前面已经查找了 i 个元素,但cnt == 0 ,这说明前面i 个元素都没有 majority,或者有 majority,但是出现的次数少于 i / 2 ;
因为如果多于 i / 2 的话 cnt 就一定不会为 0 。此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,因此继续查找就能找出 majority;
public int MoreThanHalfNum_Solution(int[] array) { int majority = array[0]; for (int i = 1, cnt = 1; i < array.length; i++) { cnt = (array[i] == majority) ? cnt + 1 : cnt - 1; if (cnt == 0) { majority = array[i]; cnt = 1; } } int cnt = 0; for (int val : array) { if (val == majority) { cnt++; } } return cnt > array.length / 2 ? majority : 0; }