题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
题解见:Number.169——多数元素
class Solution {
// 也就是寻找数组中重复次数最多的数
public int majorityElement(int[] nums) {
int len = nums.length;
int tmp = nums[0];
int counter = 1;
for (int i = 1; i < len; i++){
if (nums[i] != tmp){
counter--;
if (counter == 0){
tmp = nums[i + 1];
}
}else {
counter++;
}
}
return tmp;
}
}