一、题目内容

image.png

二、题解

解法1:

思路

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

    代码

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. int suspect = 0,votes = 0;
    4. for(int num:nums){
    5. if(votes == 0){
    6. suspect = num;
    7. }
    8. int currVote = num == suspect?1:-1;
    9. votes+=currVote;
    10. }
    11. return suspect;
    12. }
    13. }