题目
思路
- 摩尔投票法:适用于一定存在众数的情况下,需要一个计数器votes记录投票,需要一个x记录当前候选人,当votes=0时,x就设置为当前值。如果votes不等于0,则x必定保存某个候选人,我们只需看当前值是否和候选人一样,一样votes+1,否则votes-1,最后得到的数一定是出现多次的数
代码
多数元素class Solution {public int majorityElement(int[] nums) {int votes = 0, x = 0;for (int num : nums) {if (votes == 0) x = num;votes += num == x ? 1 : -1;}return x;}}
