一、题目内容

image.png

二、题解

解法1:

思路

思路

  • 排序去中位数
  • 利用hashmap求value大于length/2的数
  • 投票法,假设某个数是众数,则票数+1,遇到非嫌疑众数的数,票数-1,当票数为0则说明当前数不是众数

    代码

    1. public class Solution {
    2. public int MoreThanHalfNum_Solution(int [] array) {
    3. int votes = 0;
    4. int suspect = 0;
    5. for(int i = 0; i<array.length; i++){
    6. if(votes == 0){
    7. suspect = array[i];
    8. }
    9. int currVote = array[i] == suspect?1:-1;
    10. votes+= currVote;
    11. }
    12. return suspect;
    13. }
    14. }