解题思路:
1.从该数组[1, 2, 3, 2, 2, 2, 5, 4, 2]
的第一个数1
开始, 假设1
是题中要找出的数字x
, 那么票数votes
为+1
2.数组第二个数字2
不是x
, 那么票数votes
为-1
3.该数组的前两项票数和为0
4.接下来假设数组的第三个数3
是题中要找出的数字x
, 那么票数votes
为-1
5.数组第四个数字2
是x
, 那么票数votes
为+1
6.该数组的第三项和第四项票数和为0
…
依次类推
就可得出x
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int votes = 0, x = 0, count = 0;
for(int num : array){
if(votes == 0){
x = num;
}
votes += num == x ? 1 : -1;
}
for(int num : array){
if(num == x){
count++;
}
}
return count > array.length / 2 ? x : 0;
}
}