一、题目内容
二、题解
解法1:
思路
思路
- 排序去中位数
- 利用hashmap求value大于length/2的数
- 投票法,假设某个数是众数,则票数+1,遇到非嫌疑众数的数,票数-1,当票数为0则说明当前数不是众数
代码
public class Solution {public int MoreThanHalfNum_Solution(int [] array) {int votes = 0;int suspect = 0;for(int i = 0; i<array.length; i++){if(votes == 0){suspect = array[i];}int currVote = array[i] == suspect?1:-1;votes+= currVote;}return suspect;}}
