题目

image.png

思路

  • 摩尔投票法:适用于一定存在众数的情况下,需要一个计数器votes记录投票,需要一个x记录当前候选人,当votes=0时,x就设置为当前值。如果votes不等于0,则x必定保存某个候选人,我们只需看当前值是否和候选人一样,一样votes+1,否则votes-1,最后得到的数一定是出现多次的数

    代码

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. int votes = 0, x = 0;
    4. for (int num : nums) {
    5. if (votes == 0) x = num;
    6. votes += num == x ? 1 : -1;
    7. }
    8. return x;
    9. }
    10. }
    多数元素